Пример #1
0
 /**
  * 从响应中获取body信息
  *
  * @param res
  * @return String
  */
 @SuppressWarnings("deprecation")
 private String getResBody(HttpResponse res) {
   String strResult = "";
   if (res == null) return strResult;
   if (res.getStatusLine().getStatusCode() == 200) {
     try {
       strResult = strResult + EntityUtils.toString(res.getEntity(), charset);
     } catch (ParseException e) {
       log.error("获取body信息异常450:");
       log.error(e.getMessage());
       strResult = e.getMessage().toString();
     } catch (IOException e) {
       log.error("获取body信息异常454:");
       log.error(e.getMessage());
       strResult = e.getMessage().toString();
     }
   } else if (res.getStatusLine().getStatusCode() == 302) {
     String url = res.getLastHeader("Location").getValue();
     res.setStatusCode(200);
     strResult = url;
     return strResult;
   } else {
     strResult = "Error Response:" + res.getStatusLine().toString();
     if (res.getEntity() != null) {
       try {
         res.getEntity().consumeContent();
       } catch (IOException e) {
         log.error("获取body信息异常469:");
         log.error(e.getMessage());
       }
     }
   }
   return strResult;
 }
Пример #2
0
  private void sendProposal(
      String capabilities2, String rate2, String email2, String subject2, String message2) {
    // Log.d("TAG",key);
    MyHttpClient client = new MyHttpClient(Proposal.this);

    HttpPost post = new HttpPost("https://helium.staffittome.com/apis/create_proposal");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("session_key", staffkey));
    nameValuePairs.add(new BasicNameValuePair("capability_id", capabilities2));
    nameValuePairs.add(new BasicNameValuePair("payment_method", "1"));
    nameValuePairs.add(new BasicNameValuePair("rate", rate2));
    nameValuePairs.add(new BasicNameValuePair("email", email2));
    nameValuePairs.add(new BasicNameValuePair("subject", subject2));
    nameValuePairs.add(new BasicNameValuePair("message", message2));

    try {
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = client.execute(post, responseHandler);
      Log.d("TAG", "TEST RESULTS FROM HTTPS SEND PROPOSAL IS: " + responseBody);
      Toast.makeText(getApplicationContext(), responseBody, 0).show();

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
Пример #3
0
  private AccountInfo checkIn(AccountInfo acc) {
    // TODO Auto-generated method stub
    if (client == null) {
      acc.state = UNKNOWN_FAIL;
      return acc;
    }
    ArrayList<BasicNameValuePair> valueList = new ArrayList<BasicNameValuePair>();
    try {
      UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valueList, "UTF-8");
      HttpPost post = new HttpPost("http://www.xiami.com/task/signin");
      post.setHeader("Referer", "http://www.xiami.com/");
      post.setEntity(urlEncodedFormEntity);
      HttpResponse response = client.execute(post);
      if (response.getStatusLine().getStatusCode() == 200) {
        acc = isCheck(acc);
        if (acc.day > 0) acc.state = SUCCESS;
        else acc.state = CHECK_FAIL;
      } else {
        acc.state = SERVER_FAIL;
      }
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return acc;
  }
Пример #4
0
  /** 执行post */
  public String doHttpPost(String url, NameValuePair... nameValuePairs)
      throws AuthorizationException, XmlParserParseException, XmlParserException, IOException {
    HttpPost httpPost = createHttpPost(url, nameValuePairs);

    HttpResponse response = executeHttpRequest(httpPost);
    switch (response.getStatusLine().getStatusCode()) {
      case 200:
        try {
          return EntityUtils.toString(response.getEntity());
        } catch (ParseException e) {
          throw new XmlParserParseException(e.getMessage());
        }

      case 401:
        response.getEntity().consumeContent();
        throw new AuthorizationException(response.getStatusLine().toString());

      case 404:
        response.getEntity().consumeContent();
        throw new XmlParserException(response.getStatusLine().toString());

      default:
        response.getEntity().consumeContent();
        throw new XmlParserException(response.getStatusLine().toString());
    }
  }
Пример #5
0
 private String search() {
   String query = "sessionId=" + Sscion.getSsid() + "&" + "pageno=" + 1;
   HttpGet httpRequest = new HttpGet(URLs.ASK_URL + query);
   String strResult = " ";
   try {
     HttpClient httpClient = new DefaultHttpClient();
     HttpResponse httpResponse = httpClient.execute(httpRequest);
     if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
       strResult = EntityUtils.toString(httpResponse.getEntity());
     }
     result = JsonUtils.fjson2(strResult);
   } catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ParseException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return result;
 }
  public static Long getProjectIdByName(String projectName, RestClient restClient) {

    Long projectId = 0L;

    HttpResponse response = null;
    try {
      response =
          restClient
              .getHttpclient()
              .execute(
                  new HttpGet(
                      restClient.getUrl()
                          + "/flex/services/rest/latest/project?name="
                          + URLEncoder.encode(projectName, "utf-8")),
                  restClient.getContext());
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode >= 200 && statusCode < 300) {
      HttpEntity entity = response.getEntity();
      String string = null;
      try {
        string = EntityUtils.toString(entity);
      } catch (ParseException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      try {
        JSONArray projArray = new JSONArray(string);
        List<Long> projectIdList = new ArrayList<Long>();
        for (int i = 0; i < projArray.length(); i++) {
          Long id = projArray.getJSONObject(i).getLong("id");
          projectIdList.add(id);
        }

        Collections.sort(projectIdList);
        projectId = projectIdList.get(0);

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

    } else {
      try {
        throw new ClientProtocolException("Unexpected response status: " + statusCode);
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      }
    }

    return projectId;
  }
Пример #7
0
  private AccountInfo loginIn(AccountInfo acc) {
    // TODO Auto-generated method stub
    if (client == null) {
      acc.state = UNKNOWN_FAIL;
      return acc;
    }
    ArrayList<BasicNameValuePair> valueList = new ArrayList<BasicNameValuePair>();
    BasicNameValuePair value = null;
    value = new BasicNameValuePair("email", acc.name);
    valueList.add(value);
    value = new BasicNameValuePair("password", acc.pass);
    valueList.add(value);
    value = new BasicNameValuePair("LoginButton", "登录");
    valueList.add(value);

    try {
      UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valueList, "UTF-8");
      HttpPost post = new HttpPost("http://www.xiami.com/web/login");
      post.setHeader("Referer", "http://www.xiami.com/web/login");
      post.setEntity(urlEncodedFormEntity);
      HttpResponse response = client.execute(post);

      if (response.getStatusLine().getStatusCode() == 200) {
        String res = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (res.contains("会员登录")) {
          if (res.contains("请输入验证码")) {
            acc.state = LOGIN_VALIDATE_FAIL;
          } else {
            acc.state = LOGIN_FAIL;
          }
        } else if (res.contains("快捷操作")) {
          acc = isCheck(acc);
          if (acc.day > 0) acc.state = IS_CHECKED;
          else acc.state = SUCCESS;
        } else {
          acc.state = SERVER_FAIL;
        }
      } else {
        acc.state = SERVER_FAIL;
      }
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return acc;
  }
  private boolean setHttpEntity(HttpPost httpPost, JSONObject postEntity) {
    try {
      httpPost.setEntity(new StringEntity(postEntity.toString()));
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
      Log.e(Global.TAG, "Application update http entity error");

      return false;
    } catch (ParseException e) {
      e.printStackTrace();
      Log.e(Global.TAG, "Application update http entity error");

      return false;
    }

    return true;
  }
Пример #9
0
  public JSONArray get(String url) {
    HttpGet request = new HttpGet(url);
    DefaultHttpClient client = new DefaultHttpClient();

    try {
      HttpResponse response = client.execute(request);
      return new JSONArray(EntityUtils.toString(response.getEntity(), "UTF-8"));
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return null;
  }
Пример #10
0
 /** 发送 get请求 */
 public void get() {
   CloseableHttpClient httpclient = HttpClients.createDefault();
   try {
     // 创建httpget.
     HttpGet httpget = new HttpGet("http://www.baidu.com");
     // httpget.addHeader("Content-Type","application/x-www-form-urlencoded; charset=GBK");
     System.out.println("executing request " + httpget.getURI());
     // 执行get请求.
     CloseableHttpResponse response = httpclient.execute(httpget);
     try {
       // 获取响应实体
       HttpEntity entity = response.getEntity();
       System.out.println("--------------------------------------");
       // 打印响应状态
       System.out.println(response.getStatusLine());
       if (entity != null) {
         //					String responseString = new String(EntityUtils.toString(entity).getBytes("gbk"));
         //					responseString = new String(responseBody.getBytes("ISO-8859-1"),"UTF-8");
         //					System.out.println(responseString);
         // 打印响应内容长度
         System.out.println("Response content length: " + entity.getContentLength());
         // 打印响应内容
         System.out.println("Response content: " + EntityUtils.toString(entity));
       }
       System.out.println("------------------------------------");
     } finally {
       response.close();
     }
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (ParseException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     // 关闭连接,释放资源
     try {
       httpclient.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Пример #11
0
  /** header由調用者set Create by : 2015年9月14日 上午11:54:59 */
  private String doPost(HttpPost httpPost) throws Exception {
    try {
      httpPost.setConfig(config);
      /**
       * setHeader(name, value):如果Header中没有定义则添加,如果已定义则用新的value覆盖原用value值。 addHeader(name,
       * value):如果Header中没有定义则添加,如果已定义则保持原有value不改变。
       */
      //			httpPost.addHeader( HTTP.CONTENT_TYPE, "application/json" ) ;
      //			httpPost.addHeader( "Accept-Charset", "gbk,GB2312,utf-8;q=0.7,*;q=0.7" ) ;
      //			httpPost.addHeader( "Accept-Language", "zh-cn,zh;q=0.5" ) ;
      //			httpPost.addHeader( HTTP.CONN_DIRECTIVE, "keep-alive" ) ;
      //			httpPost.addHeader( "refer", "localhost" ) ;
      //			httpPost.addHeader( HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2)
      // Gecko/20100101 Firefox/6.0.2" ) ;

      CloseableHttpResponse response = httpClient.execute(httpPost, HttpClientContext.create());
      try {
        HttpEntity entity = response.getEntity();
        logger.debug("{}", entity);

        return EntityUtils.toString(entity);
        //				return EntityUtils.toString( entity, "utf-8" );
      } finally {
        if (null != response) response.close();
      }
    } catch (ClientProtocolException e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    } catch (ParseException e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    } catch (IOException e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    } catch (Exception e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    }
  }
Пример #12
0
  @Override
  public List<City> consume_response(Object data) {
    List<City> cities = null;
    if (data != null) {
      if (data instanceof HttpResponse) {
        // Expecting the json response
        try {
          //
          String jsonStr = EntityUtils.toString(((HttpResponse) data).getEntity());
          JSONTokener jsonTokener = new JSONTokener(jsonStr);
          JSONArray jsonArray = new JSONArray(jsonTokener);

          cities = new ArrayList<City>(jsonArray.length());
          int length = jsonArray.length();

          for (int i = 0; i < length; i++) {
            JSONObject jsonCity = (JSONObject) jsonArray.get(i);
            City city = new City();
            city.set_id(Integer.toString(jsonCity.getInt("_id")));
            city.setName(jsonCity.getString("name"));
            city.setType(jsonCity.getString("type"));

            JSONObject jsonCityGeoPos = (JSONObject) jsonCity.get("geo_position");
            city.setLongitutde(Double.toString(jsonCityGeoPos.getDouble("longitude")));
            city.setLat(Double.toString(jsonCityGeoPos.getDouble("latitude")));

            cities.add(city);
          }
        } catch (ParseException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return cities;
  }
Пример #13
0
  public static String get(String url) {
    String body = null;
    try {
      // Get请求
      HttpGet httpget = new HttpGet(url);
      System.out.println(
          "url:"
              + httpget.getURI().toString()
              + "?"
              + "func=013001&catName=S0NTeGiEvFO+eQdgmEL3j5a4KITbfTegqp2M9Ef4/Yc=");
      httpget.setURI(
          new URI(
              httpget.getURI().toString()
                  + "?"
                  + "func=013001&catName=S0NTeGiEvFO+eQdgmEL3j5a4KITbfTegqp2M9Ef4/Yc="));
      // 设置头
      // 发送请求
      HttpResponse httpresponse = httpClient.execute(httpget);

      // 获取返回数据
      HttpEntity entity = httpresponse.getEntity();
      body = EntityUtils.toString(entity);
    } catch (ParseException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } finally {
      // 关闭连接,释放资源
      httpClient.getConnectionManager().shutdown();
    }
    return body;
  }
  private JSONObject getResponseAsJSON(HttpResponse response) {
    JSONObject responseJson;

    try {
      responseJson = new JSONObject(EntityUtils.toString(response.getEntity()));
    } catch (ParseException e) {
      e.printStackTrace();
      Log.e(Global.TAG, "Application content downloader response to JSON error");

      return null;
    } catch (JSONException e) {
      e.printStackTrace();
      Log.e(Global.TAG, "Application content downloader response to JSON error");

      return null;
    } catch (IOException e) {
      e.printStackTrace();
      Log.e(Global.TAG, "Application content downloader response to JSON error");

      return null;
    }

    return responseJson;
  }
Пример #15
0
  static void getTokensFromCode() {
    access_token = null;
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("/home/sead/refresh.txt").delete();

    if (gProps == null) {
      initGProps();
    }
    // Query for token now that user has gone through browser part
    // of
    // flow
    HttpPost tokenRequest = new HttpPost(gProps.token_uri);

    MultipartEntityBuilder tokenRequestParams = MultipartEntityBuilder.create();
    tokenRequestParams.addTextBody("client_id", gProps.client_id);
    tokenRequestParams.addTextBody("client_secret", gProps.client_secret);
    tokenRequestParams.addTextBody("code", device_code);
    tokenRequestParams.addTextBody("grant_type", "http://oauth.net/grant_type/device/1.0");

    HttpEntity reqEntity = tokenRequestParams.build();

    tokenRequest.setEntity(reqEntity);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
      response = httpclient.execute(tokenRequest);

      if (response.getStatusLine().getStatusCode() == 200) {
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
          String responseJSON = EntityUtils.toString(resEntity);
          ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
          access_token = root.get("access_token").asText();
          refresh_token = root.get("refresh_token").asText();
          token_start_time = System.currentTimeMillis() / 1000;
          expires_in = root.get("expires_in").asInt();
        }
      } else {
        log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
      }
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      if (response != null) {
        try {
          response.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      try {
        httpclient.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  public static Map<Long, String> getAllProjects(RestClient restClient) {

    Map<Long, String> projects = new TreeMap<Long, String>();

    HttpResponse response = null;

    final String url = URL_GET_PROJECTS.replace("{SERVER}", restClient.getUrl());
    try {
      response = restClient.getHttpclient().execute(new HttpGet(url), restClient.getContext());
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (HttpHostConnectException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode >= 200 && statusCode < 300) {
      HttpEntity entity = response.getEntity();
      String string = null;
      try {
        string = EntityUtils.toString(entity);
      } catch (ParseException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      try {
        JSONObject projObject = new JSONObject(string);
        JSONArray projArray = projObject.getJSONArray("projects");
        for (int i = 0; i < projArray.length(); i++) {
          JSONObject project = projArray.getJSONObject(i);
          Long id = project.getLong("id");
          String projName = project.getString("name");
          JSONArray issueTypes = project.getJSONArray("issuetypes");

          boolean issueTypeTesstExists = false;
          for (int j = 0; j < issueTypes.length(); j++) {
            JSONObject issueType = issueTypes.getJSONObject(j);
            String issueTypeName = issueType.getString("name");

            if (issueTypeName.trim().equalsIgnoreCase(TEST_ISSSUETYPE_NAME)) {
              issueTypeTesstExists = true;
              break;
            }
          }

          if (!issueTypeTesstExists) {
            continue;
          }
          projects.put(id, projName);
        }

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

    } else {

      projects.put(0L, "No Project");
      try {
        throw new ClientProtocolException("Unexpected response status: " + statusCode);
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      }
    }

    return projects;
  }
Пример #17
0
  static void getTokenFromRefreshToken() {
    access_token = null;
    expires_in = -1;
    token_start_time = -1;

    if (gProps == null) {
      initGProps();
    }

    /* Try refresh token */
    // Query for token now that user has gone through browser part
    // of
    // flow

    // The method used in getTokensFromCode should work here as well - I
    // think URL encoded Form is the recommended way...
    HttpPost post = new HttpPost(gProps.token_uri);
    post.addHeader("accept", "application/json");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("client_id", gProps.client_id));
    nameValuePairs.add(new BasicNameValuePair("client_secret", gProps.client_secret));
    nameValuePairs.add(new BasicNameValuePair("refresh_token", refresh_token));
    nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));

    try {
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }

    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
      try {
        response = httpclient.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
          HttpEntity resEntity = response.getEntity();
          if (resEntity != null) {
            String responseJSON = EntityUtils.toString(resEntity);
            ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
            access_token = root.get("access_token").asText();
            // refresh_token =
            // root.get("refresh_token").asText();
            token_start_time = System.currentTimeMillis() / 1000;
            expires_in = root.get("expires_in").asInt();
          }
        } else {
          log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
          HttpEntity resEntity = response.getEntity();
        }
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        log.error("Error obtaining access token: " + e.getMessage());
      } finally {
        if (response != null) {
          response.close();
        }
        httpclient.close();
      }
    } catch (IOException io) {
      log.error("Error closing connections: " + io.getMessage());
    }
  }
  /**
   * Opens the connection to a http server or proxy.
   *
   * @return the opened low level connection
   * @throws IOException if the connection fails for any reason.
   */
  @Override
  AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    if (mProxyHost != null) {
      // If we have a proxy set, we first send a CONNECT request
      // to the proxy; if the proxy returns 200 OK, we negotiate
      // a secure connection to the target server via the proxy.
      // If the request fails, we drop it, but provide the event
      // handler with the response status and headers. The event
      // handler is then responsible for cancelling the load or
      // issueing a new request.
      AndroidHttpClientConnection proxyConnection = null;
      Socket proxySock = null;
      try {
        proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());

        proxySock.setSoTimeout(60 * 1000);

        proxyConnection = new AndroidHttpClientConnection();
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        proxyConnection.bind(proxySock, params);
      } catch (IOException e) {
        if (proxyConnection != null) {
          proxyConnection.close();
        }

        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to establish a connection to the proxy";
        }

        throw new IOException(errorMessage);
      }

      StatusLine statusLine = null;
      int statusCode = 0;
      Headers headers = new Headers();
      try {
        BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());

        // add all 'proxy' headers from the original request, we also need
        // to add 'host' header unless we want proxy to answer us with a
        // 400 Bad Request
        for (Header h : req.mHttpRequest.getAllHeaders()) {
          String headerName = h.getName().toLowerCase(Locale.ROOT);
          if (headerName.startsWith("proxy")
              || headerName.equals("keep-alive")
              || headerName.equals("host")) {
            proxyReq.addHeader(h);
          }
        }

        proxyConnection.sendRequestHeader(proxyReq);
        proxyConnection.flush();

        // it is possible to receive informational status
        // codes prior to receiving actual headers;
        // all those status codes are smaller than OK 200
        // a loop is a standard way of dealing with them
        do {
          statusLine = proxyConnection.parseResponseHeader(headers);
          statusCode = statusLine.getStatusCode();
        } while (statusCode < HttpStatus.SC_OK);
      } catch (ParseException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      } catch (HttpException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      } catch (IOException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      }

      if (statusCode == HttpStatus.SC_OK) {
        try {
          sslSock =
              (SSLSocket)
                  getSocketFactory()
                      .createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true);
        } catch (IOException e) {
          if (sslSock != null) {
            sslSock.close();
          }

          String errorMessage = e.getMessage();
          if (errorMessage == null) {
            errorMessage = "failed to create an SSL socket";
          }
          throw new IOException(errorMessage);
        }
      } else {
        // if the code is not OK, inform the event handler
        ProtocolVersion version = statusLine.getProtocolVersion();

        req.mEventHandler.status(
            version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase());
        req.mEventHandler.headers(headers);
        req.mEventHandler.endData();

        proxyConnection.close();

        // here, we return null to indicate that the original
        // request needs to be dropped
        return null;
      }
    } else {
      // if we do not have a proxy, we simply connect to the host
      try {
        sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
        sslSock.setSoTimeout(SOCKET_TIMEOUT);
      } catch (IOException e) {
        if (sslSock != null) {
          sslSock.close();
        }

        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to create an SSL socket";
        }

        throw new IOException(errorMessage);
      }
    }

    // do handshake and validate server certificates
    SslError error =
        CertificateChainValidator.getInstance()
            .doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());

    // Inform the user if there is a problem
    if (error != null) {
      // handleSslErrorRequest may immediately unsuspend if it wants to
      // allow the certificate anyway.
      // So we mark the connection as suspended, call handleSslErrorRequest
      // then check if we're still suspended and only wait if we actually
      // need to.
      synchronized (mSuspendLock) {
        mSuspended = true;
      }
      // don't hold the lock while calling out to the event handler
      boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
      if (!canHandle) {
        throw new IOException("failed to handle " + error);
      }
      synchronized (mSuspendLock) {
        if (mSuspended) {
          try {
            // Put a limit on how long we are waiting; if the timeout
            // expires (which should never happen unless you choose
            // to ignore the SSL error dialog for a very long time),
            // we wake up the thread and abort the request. This is
            // to prevent us from stalling the network if things go
            // very bad.
            mSuspendLock.wait(10 * 60 * 1000);
            if (mSuspended) {
              // mSuspended is true if we have not had a chance to
              // restart the connection yet (ie, the wait timeout
              // has expired)
              mSuspended = false;
              mAborted = true;
              if (HttpLog.LOGV) {
                HttpLog.v(
                    "HttpsConnection.openConnection():"
                        + " SSL timeout expired and request was cancelled!!!");
              }
            }
          } catch (InterruptedException e) {
            // ignore
          }
        }
        if (mAborted) {
          // The user decided not to use this unverified connection
          // so close it immediately.
          sslSock.close();
          throw new SSLConnectionClosedByUserException("connection closed by the user");
        }
      }
    }

    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);

    return conn;
  }
Пример #19
0
 /** HttpClient连接SSL */
 public void ssl() {
   CloseableHttpClient httpclient = null;
   try {
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
     FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
     try {
       // 加载keyStore d:\\tomcat.keystore
       trustStore.load(instream, "123456".toCharArray());
     } catch (CertificateException e) {
       e.printStackTrace();
     } finally {
       try {
         instream.close();
       } catch (Exception ignore) {
       }
     }
     // 相信自己的CA和所有自签名的证书
     SSLContext sslcontext =
         SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
     // 只允许使用TLSv1协议
     SSLConnectionSocketFactory sslsf =
         new SSLConnectionSocketFactory(
             sslcontext,
             new String[] {"TLSv1"},
             null,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
     // 创建http请求(get方式)
     HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
     System.out.println("executing request" + httpget.getRequestLine());
     CloseableHttpResponse response = httpclient.execute(httpget);
     try {
       HttpEntity entity = response.getEntity();
       System.out.println("----------------------------------------");
       System.out.println(response.getStatusLine());
       if (entity != null) {
         System.out.println("Response content length: " + entity.getContentLength());
         System.out.println(EntityUtils.toString(entity));
         EntityUtils.consume(entity);
       }
     } finally {
       response.close();
     }
   } catch (ParseException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   } finally {
     if (httpclient != null) {
       try {
         httpclient.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }