如何使用JSON参数向HttpURLConnection发送请求到服务器

时间:2016-04-04 06:28:38

标签: android json web-services android-activity httpurlconnection

我需要使用HttpURLConnection将json请求发送到服务器以上传图像。与HttpClient一起工作正常。但我想用HttpURLConnection和MultipartEntity提出请求。有人帮我..

以下是HttpClient的代码:

public class MultiPartRequest extends AsyncTask<Object, Integer, JSONObject> {

private AsyncHttpCallback listener;
private final String TAG = "HTTP_MULTIPART";
private Activity activity;

public MultiPartRequest(Activity activity) {
    this.activity = activity;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected JSONObject doInBackground(Object... inputParams) {
    String requestUrl = (String) inputParams[0];
    JSONObject multipartParams = (JSONObject) inputParams[1];
    HashMap<String, Object> requestObject = (HashMap<String, Object>) inputParams[2];
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject finalResult = new JSONObject();
    try {
        finalResult = new JSONObject("{\"error\":true,\"message\":\"Something went wrong\"}");
        HttpPost httpPost = new HttpPost(requestUrl);
        StringEntity entity = new StringEntity(multipartParams.toString());
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        // httpPost.setParams(multipartParams);
        MultipartEntity multipartEntity = new MultipartEntity();

        for (Entry<String, Object> obj : requestObject.entrySet()) {
            String fileName = obj.getKey();
            Log.d("Multipart", fileName);
            if (fileName.equalsIgnoreCase("data")) {
                Log.d("objectdata", obj.getValue().toString());
                multipartEntity.addPart(fileName, (StringBody) obj.getValue());
            } else {
                multipartEntity.addPart(fileName, (FileBody) obj.getValue());
            }
        }

        httpPost.setEntity(multipartEntity);
        HttpResponse response = httpClient.execute(httpPost);

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();

        for (String line = null; (line = reader.readLine()) != null; ) {
            builder.append(line).append("\n");
        }

        JSONTokener tokener = new JSONTokener(builder.toString());
        finalResult = new JSONObject(tokener);

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return finalResult;
}

@Override
public void onPostExecute(JSONObject result) {
    Log.d(TAG, "The response object is: " + result.toString());

    try {
        String errorMsg = JSONHandler.getStringFromJSONObject(result, "message");
        if (errorMsg.equalsIgnoreCase("Authentication problem with the token provided") || JSONHandler.getIntFromJSONObject(result, "code") == 5100) {
            MyApplication.displayToast(errorMsg);

            Intent intent = activity.getBaseContext().getPackageManager().getLaunchIntentForPackage(activity.getBaseContext().getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            activity.startActivity(intent);
            return;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (result.has("error")) {
        listener.errorCallback(result);
    } else {
        listener.successCallback(result);
    }
}

public void setOnResultsListener(AsyncHttpCallback listener) {
    this.listener = listener;
} }

1 个答案:

答案 0 :(得分:0)

使用Volley将图像发送到服务器。

您可以看到此链接 Android Volley Library: How to send an image to server?