/** 构造HttpPut */
  protected HttpUriRequest generateHttpRequest() {
    // 生成Http请求
    String resource =
        httpTool.generateCanonicalizedResource(
            "/" + objectGroup.getBucketName() + "/" + objectGroup.getName());
    String requestUri = OSS_END_POINT + resource;
    HttpPut httpPut = new HttpPut(requestUri);

    // 构造HttpPut
    String authorization =
        OSSHttpTool.generateAuthorization(
            accessId,
            accessKey,
            httpMethod.toString(),
            "",
            objectGroupMetaData.getContentType(),
            Helper.getGMTDate(),
            OSSHttpTool.generateCanonicalizedHeader(objectGroupMetaData.getAttrs()),
            resource);

    httpPut.setHeader(AUTHORIZATION, authorization);
    httpPut.setHeader(DATE, Helper.getGMTDate());
    httpPut.setHeader(HOST, OSS_HOST);

    try {
      httpPut.setEntity(new StringEntity(generateHttpEntity()));
    } catch (UnsupportedEncodingException e) {
      //            Log.e(this.getClass().getName(), e.getMessage());
    }

    return httpPut;
  }
 /**
  * this class takes in the new edited interest and puts the edited interest's description into the
  * user profile. The Http Client sends an HTTP PUT request to the API to update a new interest.
  * The API sends information which is stored in Android via JSON to the webserver. Here new
  * interests belonged to the user are created.
  *
  * @param type
  * @param description
  * @throws JSONException
  * @throws ClientProtocolException
  * @throws IOException
  */
 public void editInterest(String type, String description)
     throws JSONException, ClientProtocolException, IOException {
   HttpClient client = new DefaultHttpClient();
   HttpPut put =
       new HttpPut(
           "http://myapp-gosuninjas.dotcloud.com/api/v1/createinterest/"
               + UserProfile.interestpoint
               + "/");
   put.setHeader("Content-type", "application/json");
   put.setHeader("Accept", "application/json");
   JSONObject obj = new JSONObject();
   obj.put("type_interest", type);
   obj.put("description", description);
   obj.put("user", UserProfile.myuserid);
   try {
     put.setEntity(new StringEntity(obj.toString(), "UTF-8"));
   } catch (UnsupportedEncodingException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   try {
     HttpResponse response = client.execute(put);
   } catch (ClientProtocolException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
 }
  @Test
  public void testKeepAlive() throws Exception {
    String url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/pin/a14";

    HttpPut request = new HttpPut(url);
    request.setHeader("Connection", "keep-alive");

    HttpGet getRequest = new HttpGet(url);
    getRequest.setHeader("Connection", "keep-alive");

    for (int i = 0; i < 100; i++) {
      request.setEntity(new StringEntity("[\"" + i + "\"]", ContentType.APPLICATION_JSON));

      try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());
      }

      try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) {
        assertEquals(200, response2.getStatusLine().getStatusCode());
        List<String> values = consumeJsonPinValues(response2);
        assertEquals(1, values.size());
        assertEquals(String.valueOf(i), values.get(0));
      }
    }
  }
예제 #4
0
  /**
   * Takes the extracted base URI and parameters from the {@link RequestConfig} consolidated
   * parameter type and creates a {@link HttpRequestBase} of the designated method type.
   *
   * @param uri the {@link URI} whose parameters should be populated
   * @param annotatedParams the list of {@link Param}s and the parameter objects which were
   *     annotated with them; <b>Complex objects should supply a formatted version of their String
   *     representation via {@link Object#toString()}</b>
   * @param staticParams the list of {@link Request.Param}s and the parameter objects which were
   *     annotated with them <br>
   *     <br>
   * @return the created {@link HttpRequestBase} which is an instance of {@link HttpPost} <br>
   *     <br>
   * @throws Exception when the {@link HttpRequestBase} could not be created due to an exception
   *     <br>
   *     <br>
   * @since 1.1.3
   */
  private static HttpRequestBase populatePutParameters(
      URI uri, Map<Object, Param> annotatedParams, List<Request.Param> staticParams)
      throws Exception {

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    for (Request.Param param : staticParams)
      nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));

    Set<Entry<Object, Param>> methodParams = annotatedParams.entrySet();

    for (Entry<Object, Param> entry : methodParams)
      nameValuePairs.add(
          new BasicNameValuePair(entry.getValue().value(), entry.getKey().toString()));

    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
    urlEncodedFormEntity.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    HttpPut httpPut = new HttpPut(uri);

    httpPut.setHeader(
        HttpHeaders.CONTENT_TYPE.getHeaderName(),
        ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    return httpPut;
  }
예제 #5
0
  /**
   * 通过put方式发送请求 退出农场
   *
   * @param url URL地址
   * @param params 参数 user_serial, password, farm_serial
   * @return
   * @throws Exception
   */
  public String httpdelete(String url, String tokenAuth) throws Exception {
    // 拼接请求URL
    int timeoutConnection = YunTongXun.httpclienttime;
    int timeoutSocket = YunTongXun.httpclienttime;
    HttpParams httpParameters =
        new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(
        httpParameters,
        timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which
                            // is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    // 构造HttpClient的实例
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    // 创建GET方法的实例
    HttpPut httpexit = new HttpPut(url);
    httpexit.setHeader("Authorization", tokenAuth);
    try {
      HttpResponse httpResponse = httpClient.execute(httpexit);
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      return "{status_code:" + statusCode + "}";

    } catch (Exception e) {
      return null;
    }
  }
  @Override
  protected HttpRequestBase createHttpRequestBase() {
    String bugUrl = getUrlSuffix();
    LoginToken token = ((BugzillaRestHttpClient) getClient()).getLoginToken();
    if (token != null && bugUrl.length() > 0) {
      if (bugUrl.endsWith("?")) { // $NON-NLS-1$
        bugUrl += ("token=" + token.getToken()); // $NON-NLS-1$
      } else {
        bugUrl += ("&token=" + token.getToken()); // $NON-NLS-1$
      }
    }

    HttpPut request = new HttpPut(baseUrl() + bugUrl);
    request.setHeader(CONTENT_TYPE, APPLICATION_JSON);
    request.setHeader(ACCEPT, APPLICATION_JSON);
    return request;
  }
 @Test
 public void unsupportedContentType() throws Exception {
   HttpPut put = new HttpPut(URI.create(getEndpoint().toString() + "Rooms('1')"));
   put.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.TEXT_PLAIN);
   final HttpResponse response = getHttpClient().execute(put);
   assertEquals(
       HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE.getStatusCode(),
       response.getStatusLine().getStatusCode());
 }
예제 #8
0
 protected static HttpResponse doPut(String resource, String body) throws Exception {
   DefaultHttpClient client = new DefaultHttpClient();
   HttpPut put = new HttpPut(AppFabricTestBase.getEndPoint(resource));
   if (body != null) {
     put.setEntity(new StringEntity(body));
   }
   put.setHeader(AUTH_HEADER);
   return client.execute(put);
 }
예제 #9
0
  /** 构造HttpPut */
  protected HttpUriRequest generateHttpRequest() {
    // 生成Http请求
    String resource = httpTool.generateCanonicalizedResource("/" + bucketName + "/" + objectKey);
    String requestUri = OSS_END_POINT + resource;
    HttpPut httpPut = new HttpPut(requestUri);

    // 构造HttpPut
    String dateStr = Helper.getGMTDate();
    String xossHeader = OSSHttpTool.generateCanonicalizedHeader(objectMetaData.getAttrs());
    String authorization =
        OSSHttpTool.generateAuthorization(
            accessId,
            accessKey,
            httpMethod.toString(),
            "",
            objectMetaData.getContentType(),
            dateStr,
            xossHeader,
            resource);

    httpPut.setHeader(AUTHORIZATION, authorization);
    httpPut.setHeader(DATE, dateStr);
    httpPut.setHeader(HOST, OSS_HOST);

    OSSHttpTool.addHttpRequestHeader(httpPut, CACHE_CONTROL, objectMetaData.getCacheControl());
    OSSHttpTool.addHttpRequestHeader(
        httpPut, CONTENT_DISPOSITION, objectMetaData.getContentDisposition());
    OSSHttpTool.addHttpRequestHeader(
        httpPut, CONTENT_ENCODING, objectMetaData.getContentEncoding());
    OSSHttpTool.addHttpRequestHeader(httpPut, CONTENT_TYPE, objectMetaData.getContentType());
    OSSHttpTool.addHttpRequestHeader(
        httpPut, EXPIRES, Helper.getGMTDate(objectMetaData.getExpirationTime()));

    // 加入用户自定义header
    for (Entry<String, String> entry : objectMetaData.getAttrs().entrySet()) {
      OSSHttpTool.addHttpRequestHeader(httpPut, entry.getKey(), entry.getValue());
    }

    if (this.data != null && this.data.length > 0) {
      httpPut.setEntity(new ByteArrayEntity(this.data));
    }

    return httpPut;
  }
예제 #10
0
  /**
   * 修改农场 信息 通过put方式发送请求
   *
   * @param url URL地址
   * @param params 参数
   * @return
   * @throws Exception
   */
  public String httpPut(String url, Map<String, String> map, String tokenAuth) throws Exception {
    String response = null; // 返回信息

    int timeoutConnection = YunTongXun.httpclienttime;
    int timeoutSocket = YunTongXun.httpclienttime;
    HttpParams httpParameters =
        new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(
        httpParameters,
        timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which
                            // is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    // 构造HttpClient的实例
    HttpClient httpClient = new DefaultHttpClient(httpParameters);

    // 创建GET方法的实例
    HttpPut httpPut = new HttpPut(url);
    httpPut.setHeader("Authorization", tokenAuth);
    if (map.size() >= 0) {
      MultipartEntity reqEntity = new MultipartEntity();
      if (map.keySet().contains("name"))
        reqEntity.addPart("name", new StringBody(map.get("name"), Charset.forName("UTF-8")));
      if (map.keySet().contains("location"))
        reqEntity.addPart(
            "location", new StringBody(map.get("location"), Charset.forName("UTF-8")));
      if (map.keySet().contains("lng"))
        reqEntity.addPart("lng", new StringBody(map.get("lng"), Charset.forName("UTF-8")));
      if (map.keySet().contains("lat"))
        reqEntity.addPart("lat", new StringBody(map.get("lat"), Charset.forName("UTF-8")));
      if (map.keySet().contains("description"))
        reqEntity.addPart(
            "description", new StringBody(map.get("description"), Charset.forName("UTF-8")));
      if (map.keySet().contains("logo"))
        reqEntity.addPart("logo", new FileBody(new File(map.get("logo"))));
      if (map.keySet().contains("bg"))
        reqEntity.addPart("bg", new FileBody(new File(map.get("bg"))));
      // 设置httpPost请求参数
      httpPut.setEntity(reqEntity);
    }
    try {
      HttpResponse httpResponse = httpClient.execute(httpPut);
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == HttpStatus.SC_OK) // SC_OK = 200
      {
        // 获得返回结果
        response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
      } else {
        //	response = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
        return "{status_code:" + statusCode + "}";
      }
    } catch (Exception e) {
      return null;
    }
    return response;
  }
 @Test
 public void validApplicationXmlContentType() throws Exception {
   HttpPut put = new HttpPut(URI.create(getEndpoint().toString() + "Teams('1')"));
   put.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.APPLICATION_XML);
   final HttpResponse response = getHttpClient().execute(put);
   // We expect an internal server error due to the incomplete processor implementation.
   assertEquals(
       HttpStatusCodes.INTERNAL_SERVER_ERROR.getStatusCode(),
       response.getStatusLine().getStatusCode());
 }
  private static void put(Model model, String graph, String mediaType, String lang)
      throws URISyntaxException, ClientProtocolException, IOException {
    StringWriter content = new StringWriter();
    model.write(content, lang);

    StringEntity entity = new StringEntity(content.toString(), "UTF-8");

    URI uri = uri(graph);

    HttpPut httpput = new HttpPut(uri);
    httpput.setHeader("Content-Type", mediaType);
    httpput.setHeader("Accept", "text/plain");
    httpput.setEntity(entity);

    HttpResponse response = httpclient.execute(httpput);

    assertEquals(201, response.getStatusLine().getStatusCode());

    assertEquals(0, response.getHeaders("Location").length);

    response.getEntity().consumeContent();
  }
예제 #13
0
  public static String runHttpPutCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;
    try {
      HttpParams httpParameters = new BasicHttpParams();
      int timeoutConnection = 1000;
      int timeoutSocket = 1000;
      HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
      HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
      client.setParams(httpParameters);

      HttpPut putRequest = new HttpPut(url);
      putRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
      putRequest.setHeader("Content-type", "application/json");

      HttpResponse resp = client.execute(putRequest);

      if (resp == null || resp.getEntity() == null) {
        throw new ESHttpException(
            "Unable to execute PUT URL ("
                + url
                + ") Exception Message: < Null Response or Null HttpEntity >");
      }

      isStream = resp.getEntity().getContent();

      if (resp.getStatusLine().getStatusCode() != 200) {

        throw new ESHttpException(
            "Unable to execute PUT URL ("
                + url
                + ") Exception Message: ("
                + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString())
                + ")");
      }

      return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
      logger.debug("PUT URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
      throw new ESHttpException(
          "Caught an exception during execution of URL ("
              + url
              + ")Exception Message: ("
              + e
              + ")");
    } finally {
      if (isStream != null) isStream.close();
    }
    return return_;
  }
예제 #14
0
 public HttpResponse put(
     String cType,
     String accountSid,
     String authToken,
     String timestamp,
     String url,
     DefaultHttpClient httpclient,
     EncryptUtil encryptUtil,
     String body)
     throws Exception {
   HttpPut httpPut = new HttpPut(url);
   httpPut.setHeader("Accept", cType);
   httpPut.setHeader("Content-Type", cType + ";charset=utf-8");
   String src = accountSid + ":" + timestamp;
   String auth = encryptUtil.base64Encoder(src);
   httpPut.setHeader("Authorization", auth);
   logger.info(body);
   BasicHttpEntity requestBody = new BasicHttpEntity();
   requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
   requestBody.setContentLength(body.getBytes("UTF-8").length);
   httpPut.setEntity(requestBody);
   HttpResponse response = httpclient.execute(httpPut);
   return response;
 }
예제 #15
0
  public static void setResourceAndWorkspace(String resourceName, String workspaceName)
      throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();
    jo.put("projectName", "EC-Chef-" + StringConstants.PLUGIN_VERSION);
    jo.put("resourceName", resourceName);
    jo.put("workspaceName", workspaceName);

    HttpPut httpPutRequest =
        new HttpPut(
            "http://"
                + props.getProperty(StringConstants.COMMANDER_SERVER)
                + ":8000/rest/v1.0/projects/"
                + "EC-Chef-"
                + StringConstants.PLUGIN_VERSION);

    String encoding =
        new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(
                org.apache.commons.codec.binary.StringUtils.getBytesUtf8(
                    props.getProperty(StringConstants.COMMANDER_USER)
                        + ":"
                        + props.getProperty(StringConstants.COMMANDER_PASSWORD))));

    StringEntity input = new StringEntity(jo.toString());

    input.setContentType("application/json");
    httpPutRequest.setEntity(input);
    httpPutRequest.setHeader("Authorization", "Basic " + encoding);
    HttpResponse httpResponse = httpClient.execute(httpPutRequest);

    if (httpResponse.getStatusLine().getStatusCode() >= 400) {
      throw new RuntimeException(
          "Failed to set resource  "
              + resourceName
              + " to project "
              + "EC-Chef-"
              + StringConstants.PLUGIN_VERSION);
    }
    System.out.println(
        "Set the resource as "
            + resourceName
            + " and workspace as "
            + workspaceName
            + " successfully.");
  }
  public static int cancel10x(String urlString) throws IOException, InterruptedException {

    final URI uri = OOBuildStep.URI(urlString + EXECUTIONS_API + "/status");
    final HttpPut httpPut = new HttpPut(uri);
    String body = "{\"action\":\"cancel\"}";
    StringEntity entity = new StringEntity(body);
    httpPut.setEntity(entity);
    httpPut.setHeader(
        "Content-Type", "application/json"); // this is mandatory in order for the request to work
    if (OOBuildStep.getEncodedCredentials() != null) {
      httpPut.addHeader(
          "Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
    }
    HttpResponse response = client.execute(httpPut);
    return response.getStatusLine().getStatusCode();
  }
예제 #17
0
    protected String doInBackground(String... params) {

      String resul;

      idGoogle = params[0];
      token = params[1];
      String email =
          mPlusClient.getAccountName().substring(0, mPlusClient.getAccountName().indexOf("@"));

      DefaultHttpClient httpClient = new DefaultHttpClient();

      HttpPut put = new HttpPut(WebServicesRest.USER_URL + "/" + email);

      put.setHeader("content-type", "application/json");

      try {
        // Construimos el objeto cliente en formato JSON
        User user = new User();

        user.setEmail(mPlusClient.getAccountName());
        user.setIdGoogle(idGoogle);
        user.setToken(token);

        String jsonUser = new GsonBuilder().create().toJson(user);

        ByteArrayEntity entity = new ByteArrayEntity(jsonUser.getBytes());
        put.setEntity(entity);

        HttpResponse resp = httpClient.execute(put);
        String respStr = EntityUtils.toString(resp.getEntity());

        resul = respStr;

      } catch (Exception ex) {
        Log.e("ServicioRest", "Error!", ex);
        resul = null;
      }

      return resul;
    }
  // *****************************************************************************
  // Save Contact using HTTP PUT method with singleContactUrl.
  // If Id is zero(0) a new Contact will be added.
  // If Id is non-zero an existing Contact will be updated.
  // HTTP POST could be used to add a new Contact but the ContactService knows
  // an Id of zero means a new Contact so in this case the HTTP PUT is used.
  // *****************************************************************************
  public Integer SaveContact(Contact saveContact) {
    Integer statusCode = 0;
    HttpResponse response;

    try {
      boolean isValid = true;

      // Data validation goes here

      if (isValid) {

        // POST request to <service>/SaveVehicle
        HttpPut request = new HttpPut(singleContactUrl + saveContact.getId());
        request.setHeader("User-Agent", "dev.ronlemire.contactClient");
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");

        // Build JSON string
        JSONStringer contact =
            new JSONStringer()
                .object()
                .key("Id")
                .value(Integer.parseInt(saveContact.getId()))
                .key("FirstName")
                .value(saveContact.getFirstName())
                .key("LastName")
                .value(saveContact.getLastName())
                .key("Email")
                .value(saveContact.getEmail())
                .endObject();
        StringEntity entity = new StringEntity(contact.toString());

        request.setEntity(entity);

        // Send request to WCF service
        DefaultHttpClient httpClient = new DefaultHttpClient();
        response = httpClient.execute(request);

        Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());

        // statusCode =
        // Integer.toString(response.getStatusLine().getStatusCode());
        statusCode = response.getStatusLine().getStatusCode();

        if (saveContact.getId().equals("0")) {
          // New Contact.Id is in buffer
          HttpEntity responseEntity = response.getEntity();
          char[] buffer = new char[(int) responseEntity.getContentLength()];
          InputStream stream = responseEntity.getContent();
          InputStreamReader reader = new InputStreamReader(stream);
          reader.read(buffer);
          stream.close();
          statusCode = Integer.parseInt(new String(buffer));
        } else {
          statusCode = response.getStatusLine().getStatusCode();
        }
      }

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

    return statusCode;
  }
예제 #19
0
 protected static HttpPut getPut(String resource) throws Exception {
   HttpPut put = new HttpPut(AppFabricTestBase.getEndPoint(resource));
   put.setHeader(AUTH_HEADER);
   return put;
 }
예제 #20
0
 protected static HttpResponse doPut(String resource) throws Exception {
   DefaultHttpClient client = new DefaultHttpClient();
   HttpPut put = new HttpPut(AppFabricTestBase.getEndPoint(resource));
   put.setHeader(AUTH_HEADER);
   return doPut(resource, null);
 }
예제 #21
0
파일: Network.java 프로젝트: ndong211/bo
  public NetworkState httpPutUpdateString(
      String uri, byte[] valuePairs, JSONParseInterface jsonParser) {
    // 测试代码/////////////////////////////////////////////
    // String jsonData = "[{\"id\":\"22\",\"content\":内容1},{\"id\":\"33\",\"content\":内容2}]";
    // String jsonData = "[{id:22,content:内容1},{id:33,content:内容2}]";
    // jsonParser.parsing(jsonData);    //解析
    ////////////////////////////////////////////////////////
    NetworkState netState = new NetworkState();
    //		if(wapIf()){
    //			uri="http://"+CMWAP_GATEWAY+uri.substring(uri.indexOf("/", 8));
    //		}
    int stateCode;
    HttpPut httpPut = new HttpPut(uri);
    httpPut.setHeader(
        "Accept-Language",
        (Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry()).toLowerCase());
    if (JSESSIONIDStr != null) {
      httpPut.setHeader("Cookie", "JSESSIONID=" + JSESSIONIDStr);
    }
    httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");

    try {
      httpPut.setEntity(new ByteArrayEntity(valuePairs));

      HttpResponse httpResponse = defaultHttpClient.execute(httpPut);
      stateCode = httpResponse.getStatusLine().getStatusCode();
      if (stateCode != 200) {
        netState.setNetworkState(false);
        netState.setErrorMessage(NetworkState.ERROR_SERVER_ERROR_MESSAGE);
        // Log.d("NETT", NetworkState.ERROR_SERVER_ERROR_MESSAGE+":"+stateCode+uri);
        return netState;
      }

      getCookie(defaultHttpClient);

      HttpEntity httpEntity = httpResponse.getEntity();
      InputStream is = null;
      if (httpResponse.getEntity().getContentEncoding() == null
          || httpResponse.getEntity().getContentEncoding().getValue().toLowerCase().indexOf("gzip")
              < 0) {
        is = new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity));
      } else {
        is = new GZIPInputStream(new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity)));
      }

      byte[] con = readInStream(is);
      String str = new String(con);
      if (str != null && str.indexOf("登录过期") != -1 && str.indexOf("-202") != -1) {
        if (appContext instanceof BaseActivity) {
          BaseActivity ba = ((BaseActivity) appContext);
          //////////////////////////////////////
          ba.exit();
          ba.deInit();
          ///////////////////////////////////////
          new Thread() {
            public void run() {
              // 停掉连接obd
              Intent intent = new Intent();
              intent.setAction(TongGouService.TONGGOU_ACTION_START);
              intent.putExtra("com.tonggou.server", "STOP");
              appContext.sendBroadcast(intent);
            }
          }.start();

          Intent toLogin = new Intent(appContext, LoginActivity.class);
          toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          toLogin.putExtra("tonggou.loginExpire", "登录过期,请重新登录。");
          appContext.startActivity(toLogin);
        }
      }
      TongGouApplication.showLog(str);
      // Log.d("NETT", str);
      jsonParser.parsing(str); // 解析
      netState.setNetworkState(true);

      return netState;

    } catch (IOException ie) {
      netState.setNetworkState(false);
      ie.printStackTrace();
      if (ie instanceof SocketTimeoutException) {
        if ("en".equals(Locale.getDefault().getLanguage().toLowerCase())) {

          netState.setErrorMessage(NetworkState.ERROR_CLIENT_ERROR_SOCKETTIMEOUT_MESSAGE_EN);
        } else {
          netState.setErrorMessage(NetworkState.ERROR_CLIENT_ERROR_SOCKETTIMEOUT_MESSAGE);
        }
        return netState;
      }
      if ("en".equals(Locale.getDefault().getLanguage().toLowerCase())) {
        netState.setErrorMessage(NetworkState.ERROR_CLIENT_ERROR_TIMEOUT_MESSAGE_EN);
      } else {
        netState.setErrorMessage(NetworkState.ERROR_CLIENT_ERROR_TIMEOUT_MESSAGE);
      }

    } catch (FactoryConfigurationError e) {
      netState.setNetworkState(false);
      netState.setErrorMessage(NetworkState.ERROR_RESPONSE_ERROR_MESSAGE);
    } catch (NullPointerException ex) {
      netState.setNetworkState(false);
      netState.setErrorMessage(NetworkState.ERROR_RESPONSE_ERROR_MESSAGE);
    }
    return netState;
  }
예제 #22
0
  /** 更新用户标签 */
  public void refreshRegisrer() {

    String privileges = Preferences.getPrivileges(Application.sharePref);
    if (privileges == null || privileges.equals("")) {
      return;
    }
    String mytag = "";
    try {
      JSONArray privs = new JSONArray(privileges);
      for (int i = 0; i < privs.length(); i++) {
        String name = privs.getJSONObject(i).getString("name");
        if (name != null && !name.equals("")) {
          mytag += name + ",";
        }
      }
    } catch (JSONException e1) {
      e1.printStackTrace();
    }
    List<NameValuePair> values = new ArrayList<NameValuePair>();

    String names = getPackageName();
    values.add(new BasicNameValuePair("deviceId", DeviceInfoUtil.getDeviceId(this)));
    values.add(new BasicNameValuePair("appId", cubeApplication.getAppKey()));
    String username = Preferences.getUserName(Application.sharePref);
    String sex =
        Preferences.getSex(Application.sharePref) != null
            ? Preferences.getSex(Application.sharePref)
            : "";
    String phone = Preferences.getPhone(Application.sharePref);
    // 去掉了标签的userName,phone
    values.add(new BasicNameValuePair("alias", username));
    values.add(new BasicNameValuePair("tags", "{privileges=" + mytag + "sex=" + sex + "}"));

    HttpPut request = new HttpPut(URL.CHECKIN_URL + "/tags");
    request.setHeader(
        "Accept",
        "application/x-www-form-urlencoded, application/xml, text/html, text/*, image/*, */*");
    DefaultHttpClient client = new DefaultHttpClient();
    if (values != null && values.size() > 0) {
      try {
        UrlEncodedFormEntity entity;
        entity = new UrlEncodedFormEntity(values, "utf-8");
        request.setEntity(entity);
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    try {
      HttpResponse response = client.execute(request);
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != 200) {

        return;
      }

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #23
0
  private String execute(HttpMethod method, String url, Map<String, String> paramz)
      throws IOException {
    if (!(method.equals(HttpMethod.GET)
            || method.equals(HttpMethod.DELETE)
            || method.equals(HttpMethod.PUT)
            || method.equals(HttpMethod.POST))
        || TextUtils.isEmpty(url)) {
      logger.error("Invalid request : {} | {}", method.name(), url);
      return null;
    }
    logger.trace("HTTP {} : {}", method.name(), url);
    BufferedInputStream bis = null;
    StringBuilder builder = new StringBuilder();
    int buf_size = 50 * 1024; // read in chunks of 50 KB
    ByteArrayBuffer bab = new ByteArrayBuffer(buf_size);
    String query = getEncodedParameters(paramz);
    logger.trace("Query String : {}", query);
    HttpURLConnection conn = null;
    try {
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        HttpUriRequest req = null;
        switch (method) {
          case GET:
          case DELETE:
            url = paramz.size() > 0 ? url + "?" + query : url;
            if (method.equals(HttpMethod.GET)) {
              req = new HttpGet(url);
            } else if (method.equals(HttpMethod.DELETE)) {
              req = new HttpDelete(url);
            }
            break;
          case POST:
          case PUT:
            HttpEntity entity = TextUtils.isEmpty(query) ? null : new StringEntity(query);
            BasicHeader header =
                new BasicHeader(HTTP.CONTENT_ENCODING, "application/x-www-form-urlencoded");
            if (method.equals(HttpMethod.PUT)) {
              HttpPut putr = new HttpPut(url);
              if (entity != null) {
                putr.setHeader(header);
                putr.setEntity(entity);
                req = putr;
              }
            } else if (method.equals(HttpMethod.POST)) {
              HttpPost postr = new HttpPost(url);
              if (entity != null) {
                postr.setHeader(header);
                postr.setEntity(entity);
                req = postr;
              }
            }
        }
        HttpResponse httpResponse = HttpManager.execute(req, Utils.DEV_ENV, version);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
          logger.warn("HTTP request failed with status code: {}", statusCode);
          logger.warn(httpResponse.getStatusLine().getReasonPhrase());
          throw new IOException("HTTP request failed with status code : " + statusCode);
        }
        bis = new BufferedInputStream(httpResponse.getEntity().getContent());
      } else {

        if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE)) {
          url = paramz.size() > 0 ? url + "?" + query : url;
        }
        URL uri = new URL(url);
        conn = (HttpURLConnection) uri.openConnection();
        conn.setRequestProperty("User-Agent", userAgent + "/" + version);
        conn.setDoInput(true);
        conn.setReadTimeout(60 * 1000 /* milliseconds */);
        conn.setConnectTimeout(60 * 1000 /* milliseconds */);
        conn.setRequestMethod(method.name());
        if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) {
          conn.setDoOutput(true);
          OutputStream os = conn.getOutputStream();
          BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
          writer.write(query);
          writer.close();
          os.close();
        }
        int status = conn.getResponseCode();
        if (status != HttpStatus.SC_OK) {
          logger.warn("HTTP request failed with status code: {}", status);
          logger.warn(conn.getResponseMessage());
          throw new IOException("HTTP request failed with status code : " + status);
        }
        bis = new BufferedInputStream(conn.getInputStream());
      }
      int read = 0;
      if (bis != null) {
        byte buffer[] = new byte[buf_size];
        while ((read = bis.read(buffer, 0, buf_size)) != -1) {
          // builder.append(new String(buffer, "utf-8"));
          bab.append(buffer, 0, read);
        }
        builder.append(new String(bab.toByteArray(), "UTF-8"));
      }
      if (conn != null) conn.disconnect();
    } catch (IOException e1) {
      e1.printStackTrace();
      logger.error("HTTP request failed : {}", e1);
      throw e1;
    }
    return builder.toString();
  }