簡體   English   中英

使用HttpURLConnection將Json數據發布到REST API服務器

[英]Post Json data with HttpURLConnection to REST API server

我嘗試制作一個帶有Camera Bitmap和其他數據的小應用程序,然后將它們以Json格式發送到REST API服務器。 到目前為止,我已經寫了下面的代碼,但是我得到了錯誤代碼400 Bad request :(

這是在MainActivity中

private void SendPictureToServer(String sPhoto) {

try {
    String baseUrl = "http://192.168.0.1:7100/api/v1/save/img";
    String username = "52363cc0cb3a442ebc98ba399f47ca3d";  // <= api key
    String password = "";

    JSONObject postData = new JSONObject();
    postData.put("pl", "1");
    postData.put("id", "76885");
    postData.put("name", "photo");
    postData.put("ext", "jpg");
    postData.put("type", "Product picture #1");
    postData.put("img", sPhoto);

    ApiClient apiClient = new ApiClient(baseUrl, username, password);
    AsyncTask<Void, Void, String> execute = new ExecuteNetworkOperation(apiClient, postData.toString(), "POST");
    execute.execute();
} catch (Exception e) {
    e.printStackTrace();
}

}

這也在MainActivity中

public class ExecuteNetworkOperation extends AsyncTask<Void, Void, String> {

private ApiClient apiClient;
private String isValidCredentials = "";
private String postData = "";
private String httpMethod = "";

public ExecuteNetworkOperation(ApiClient apiClient, String postData, String httpMethod) {
    this.apiClient = apiClient;
    this.postData = postData;
    this.httpMethod = httpMethod;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    // Display the progress bar.
    // findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
}

@Override
protected String doInBackground(Void... params) {
    try {
        if (httpMethod == "POST" && !TextUtils.isEmpty(postData))
        {
            apiClient.setHttpMethod("POST");
            isValidCredentials = apiClient.executePostData(postData);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    //Hide the progress bar.
    //findViewById(R.id.loadingPanel).setVisibility(View.GONE);

    if (isValidCredentials.equals("true")) {
        Toast.makeText(getApplicationContext(), "Successful connection", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_LONG).show();
    }
}

}

這是在ApiClient.java中

public class ApiClient {

private String baseUrl;
private String username;
private String password;
private String urlResource;
private String urlPath;
private String lastResponse;
private String payload;
private String httpMethod;
private HashMap<String, String> parameters;
private Map<String, List<String>> headerFields;

public ApiClient(String  baseUrl, String username, String password) {
    setBaseUrl(baseUrl);
    this.username = username;
    this.password = password;
    this.urlResource = "";
    this.urlPath = "";
    this.httpMethod = "";
    parameters = new HashMap<>();
    lastResponse = "";
    payload = "";
    headerFields = new HashMap<>();
    // This is important. The application may break without this line.
    System.setProperty("jsse.enableSNIExtension", "false");
}

public ApiClient setBaseUrl(String baseUrl) {
    this.baseUrl = baseUrl;
    if (!baseUrl.substring(baseUrl.length() - 1).equals("/")) {
        this.baseUrl += "/";
    }
    return this;
}

public ApiClient setHttpMethod(String httpMethod) {
    this.httpMethod = httpMethod;
    return this;
}

public ApiClient clearAll() {
    parameters.clear();
    baseUrl = "";
    this.username = "";
    this.password = "";
    this.urlResource = "";
    this.urlPath = "";
    this.httpMethod = "";
    lastResponse = "";
    payload = "";
    headerFields.clear();
    return this;
}   


public String executePostData(String postJsonData) {
    StringBuilder outputStringBuilder = new StringBuilder();

    try {
        String userCredentials = new String(username + ":" + password);
        String basicAuth = "Basic " + Base64.encodeToString(userCredentials.getBytes(), Base64.NO_WRAP);

        URL url = new URL(this.baseUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty ("Authorization", basicAuth);
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);

        try {

            OutputStream outputStream = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(postJsonData);
            writer.flush();
            writer.close();
            outputStream.close();

            headerFields = connection.getHeaderFields();
            int responseCode = connection.getResponseCode();
            String responseMess = connection.getResponseMessage();
            InputStream errorStream = connection.getErrorStream();

            Log.e("postJsonData ", postJsonData);
            Log.e("headerFields ", headerFields.toString());
            Log.e("ResponseCod ", String.valueOf(responseCode));
            Log.e("ResponseMessage ", responseMess);
            Log.e("ErrorStream ", errorStream.toString());


            if (responseCode == HttpURLConnection.HTTP_OK) {
                outputStringBuilder.append("true : ");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    outputStringBuilder.append(line);
                }
                bufferedReader.close();
            }else {
                outputStringBuilder.append(new String("false : "+responseCode +" " + responseMess + " " + errorStream.toString()));
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return outputStringBuilder.toString();
}

}

這是來自Logcat

07-03 18:32:19.427 30515-31533 E/headerFields: {null=[HTTP/1.1 400 Bad Request], Content-Length=[0], Date=[Tue, 03 Jul 2018 15:31:07 GMT], Server=[Microsoft-HTTPAPI/2.0], X-Android-Received-Millis=[1530631939426], X-Android-Response-Source=[NETWORK 400], X-Android-Selected-Protocol=[http/1.1], X-Android-Sent-Millis=[1530631939299]}
07-03 18:32:19.427 30515-31533 E/ResponseCod: 400
07-03 18:32:19.428 30515-31533 E/ResponseMessage: Bad Request
07-03 18:32:19.428 30515-31533 E/ErrorStream: buffer(com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@ccbe20f).inputStream()
07-03 18:32:19.428 30515-30515 E/isValidCredentials: false : 400 Bad Request buffer(com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@ccbe20f).inputStream()

這就是我發送POST的方式

讓我知道您是否需要任何澄清。

public static String executePost(String targetURL, String requestJSON, String apikey) {
        HttpURLConnection connection = null;
        InputStream is = null;

        try {
            //Create connection
            URL url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            //TODO may be prod or preprod api key
            if (apikey.equals(Constants.APIKEY_PREPROD)) {
                connection.setRequestProperty("Authorization", Constants.APIKEY_PREPROD);
            }
            if (apikey.equals(Constants.APIKEY_PROD)){
                connection.setRequestProperty("Authorization", Constants.APIKEY_PROD);
            }
            connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");  
            connection.setUseCaches(false);
            connection.setDoOutput(true);

            //Send request
            System.out.println(requestJSON);
            DataOutputStream wr = new DataOutputStream (
            connection.getOutputStream());
            wr.writeBytes(requestJSON);
            wr.close();

            //Get Response  

            try {
                is = connection.getInputStream();
            } catch (IOException ioe) {
                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConn = (HttpURLConnection) connection;
                    int statusCode = httpConn.getResponseCode();
                    if (statusCode != 200) {
                        is = httpConn.getErrorStream();
                    }
                }
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(is));


            StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

這是對我有用的解決方案。 從DroiDev提供的解決方案開始,它進行了一些小的更改。

    public static String executePost(String targetURL, String requestJSON, String apikey) {
    HttpURLConnection connection = null;
    InputStream is = null;
    String authKey = "Basic " + Base64.encodeToString((apikey + ":").getBytes(), Base64.NO_WRAP);

    try {
        //Create connection
        URL url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Authorization", authKey);
        connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
        wr.writeBytes(requestJSON);
        wr.close();

        //Get Response
        try {
            is = connection.getInputStream();
        } catch (IOException ioe) {
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection httpConn = (HttpURLConnection) connection;
                int statusCode = httpConn.getResponseCode();
                if (statusCode != 200) {
                    is = httpConn.getErrorStream();
                }
            }
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();

    } catch (Exception e) {

        e.printStackTrace();
        return null;

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM