コード例 #1
0
ファイル: HttpEngine.java プロジェクト: treejames/Practice
 private Res handleGETRequest(Req request, Class<Res> resClass) {
   Map<String, Object> paramsMap = request.getParams();
   String params = "";
   if (paramsMap != null) {
     params += "?";
     Iterator it = paramsMap.entrySet().iterator();
     while (it.hasNext()) {
       Map.Entry pairs = (Map.Entry) it.next();
       params += (pairs.getKey() + "=" + pairs.getValue());
       if (it.hasNext()) {
         params += "&";
       }
     }
   }
   String getUrl = request.getURL() + params;
   Log.d("[Request URL]", getUrl);
   HttpGet httpGet = new HttpGet(getUrl);
   Map<String, String> headersMap = request.getHeaders();
   if (headersMap != null) {
     Iterator<Map.Entry<String, String>> iterator = headersMap.entrySet().iterator();
     while (iterator.hasNext()) {
       Map.Entry<String, String> entry = iterator.next();
       httpGet.addHeader(entry.getKey(), entry.getValue());
     }
   }
   for (Header h : httpGet.getHeaders(HttpConstants.REQUEST_HEADER_DEVICE_ID)) {
     Log.d("[Request Header]", h.getName() + " --- " + h.getValue());
   }
   Res response = null;
   try {
     HttpResponse httpResponse = httpClient.execute(httpGet);
     response = (Res) resClass.newInstance().parseResult(httpResponse);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return response;
 }
コード例 #2
0
ファイル: HttpEngine.java プロジェクト: treejames/Practice
  private Res handlePOSTRequest(Req request, Class<Res> resClass) {
    L.d(TAG, "Request URL: " + request.getURL());
    HttpPost httpPost = new HttpPost(request.getURL());
    // 添加请求头
    Map<String, String> headersMap = request.getHeaders();
    if (headersMap != null) {
      Iterator<Map.Entry<String, String>> iterator = headersMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        httpPost.addHeader(entry.getKey(), entry.getValue());
      }
    }
    L.d(TAG, "Request Header: " + new Gson().toJson(headersMap));
    // 判断是否存在上传文件,以不同方式添加请求参数
    if (request.existUploadFiles()) {
      Map<String, String> uploadFilesMap = request.getUploadFiles();
      Map<String, Object> paramsMap = request.getParams();
      /*MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.setMode( HttpMultipartMode.BROWSER_COMPATIBLE );
      //			builder.setCharset( Charset.forName( "UTF-8" ) );
      String data = new Gson().toJson( paramsMap );
      // 设置中文编码
      ContentType contentType = ContentType.create( "application/json" , HTTP.UTF_8 );
      StringBody strBody = new StringBody( data , contentType );
      builder.addPart( "data" , strBody );

      //			builder.addTextBody( "data" , data );
      //			builder.addTextBody( "data" , data , ContentType.APPLICATION_JSON.withCharset( "UTF-8" ) );
      Log.d( "[File Data]" , data );
      Iterator<Entry<String , String>> iterator = uploadFilesMap.entrySet().iterator();
      while( iterator.hasNext() )
      {
      	Map.Entry<String , String> entry = iterator.next();
      	String key = entry.getKey();
      	String filePath = entry.getValue();
      	if( !TextUtils.isEmpty( filePath ) )
      	{
      		byte[] fileByte = FileUtils.getBytesFromFile( new File( filePath ) );
      		builder.addBinaryBody( key , fileByte );
      	}
      }
      HttpEntity httpEntity = builder.build();*/
      MultipartEntity httpEntity = new MultipartEntity();
      StringBody sb =
          new StringBody(
              new Gson().toJson(paramsMap), ContentType.APPLICATION_JSON.withCharset("UTF-8"));
      httpEntity.addPart("data", sb);
      Iterator<Entry<String, String>> iterator = uploadFilesMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        String key = entry.getKey();
        String filePath = entry.getValue();
        if (!TextUtils.isEmpty(filePath)) {
          /*byte[] fileByte = FileUtils.getBytesFromFile( new File( filePath ) );
          builder.addBinaryBody( key , fileByte );*/
          ContentBody cbFile = new FileBody(new File(filePath));
          httpEntity.addPart(key, cbFile);
        }
      }
      httpPost.setEntity(httpEntity);
      /*if( paramsMap != null )
      {
      	MultipartEntity httpEntity = new MultipartEntity();
      	Iterator<Map.Entry<String , Object>> iterator = paramsMap.entrySet().iterator();
      	while( iterator.hasNext() )
      	{
      		Map.Entry<String , Object> entry = iterator.next();
      		L.d( TAG , "---- Params Key: " + entry.getKey() + " ----\n---- Params Value: " + entry.getValue() );
      		StringBody sb = new StringBody( new Gson().toJson( entry.getValue() ) , ContentType.APPLICATION_JSON.withCharset( "UTF-8" ) );
      		httpEntity.addPart( entry.getKey() , sb );
      	}
      	httpPost.setEntity( httpEntity );
      }*/
    } else {
      Map<String, Object> paramsMap = request.getParams();
      L.e(TAG, "[Request Params]: " + new Gson().toJson(paramsMap));
      if (paramsMap != null) {
        String bodyJsonString = new Gson().toJson(paramsMap);
        StringEntity entity = null;
        try {
          entity = new StringEntity(bodyJsonString, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        httpPost.setEntity(entity);
      }
    }
    Res response = null;
    try {
      HttpResponse httpResponse = httpClient.execute(httpPost);
      try {
        response = (Res) resClass.newInstance().parseResult(httpResponse);
        if (response != null && response.isTokenError()) {
          EventBus.getDefault().post(new ErrorTokenEvent());
        }
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return response;
  }