當前位置: 首頁>>代碼示例>>Java>>正文


Java Consts.UTF_8屬性代碼示例

本文整理匯總了Java中org.apache.http.Consts.UTF_8屬性的典型用法代碼示例。如果您正苦於以下問題:Java Consts.UTF_8屬性的具體用法?Java Consts.UTF_8怎麽用?Java Consts.UTF_8使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在org.apache.http.Consts的用法示例。


在下文中一共展示了Consts.UTF_8屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: handle

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    StringBuilder body = new StringBuilder();
    try (InputStreamReader reader = new InputStreamReader(httpExchange.getRequestBody(), Consts.UTF_8)) {
        char[] buffer = new char[256];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            body.append(buffer, 0, read);
        }
    }
    Headers requestHeaders = httpExchange.getRequestHeaders();
    Headers responseHeaders = httpExchange.getResponseHeaders();
    for (Map.Entry<String, List<String>> header : requestHeaders.entrySet()) {
        responseHeaders.put(header.getKey(), header.getValue());
    }
    httpExchange.getRequestBody().close();
    httpExchange.sendResponseHeaders(statusCode, body.length() == 0 ? -1 : body.length());
    if (body.length() > 0) {
        try (OutputStream out = httpExchange.getResponseBody()) {
            out.write(body.toString().getBytes(Consts.UTF_8));
        }
    }
    httpExchange.close();
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:24,代碼來源:RestClientSingleHostIntegTests.java

示例2: makeRequest

private String makeRequest(String question) {
        try {
            HttpPost httpPost = new HttpPost(URL);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("query", question));
//            params.add(new BasicNameValuePair("lang", "it"));
            params.add(new BasicNameValuePair("kb", "dbpedia"));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);

            // Error Scenario
            if(response.getStatusLine().getStatusCode() >= 400) {
                logger.error("QANARY Server could not answer due to: " + response.getStatusLine());
                return null;
            }

            return EntityUtils.toString(response.getEntity());
        }
        catch(Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
 
開發者ID:dbpedia,項目名稱:chatbot,代碼行數:26,代碼來源:QANARY.java

示例3: post

public String post(String url, String jsonIn) throws IOException, InvalidHttpResponseStatusException {
    HttpPost request = new HttpPost(url);
    request.setHeader("User-Agent", getUserAgent());
    request.setHeader("Content-Type", CONTENT_TYPE);
    if (getCredentials() != null) {
        request.setHeader("Authorization", getCredentials());
    }

    if (StringUtils.isBlank(jsonIn)) {
        return service(request);
    }
    StringEntity stringEntity = new StringEntity(jsonIn, Consts.UTF_8);
    stringEntity.setContentType(CONTENT_TYPE);
    request.setEntity(stringEntity);

    return service(request);
}
 
開發者ID:ideaalloc,項目名稱:yinuo-tcp,代碼行數:17,代碼來源:BaseClient.java

示例4: call

@Override
public String call() throws IOException {
	InputStream is = null;
	try {
		final HttpGet httpPost = new HttpGet(API_PATH);
		final HttpResponse response = Downloader.downloader.getClient().execute(httpPost);

		is = response.getEntity().getContent();

		final InputStreamReader isr = new InputStreamReader(is, Consts.UTF_8);
		final BufferedReader reader = new BufferedReader(isr);

		final StringBuilder sb = new StringBuilder();
		String line;
		while ((line = reader.readLine())!=null)
			sb.append(line);
		return line;
	} finally {
		IOUtils.closeQuietly(is);
	}
}
 
開發者ID:Team-Fruit,項目名稱:EEWReciever,代碼行數:21,代碼來源:P2PQuake.java

示例5: run

@Override
public void run() {
	JsonReader jr = null;
	try {
		final HttpGet get = new HttpGet(JSON_PATH);
		final HttpResponse res = Downloader.downloader.getClient().execute(get);

		jr = new JsonReader(new InputStreamReader(res.getEntity().getContent(), Consts.UTF_8));

		final PointsJson json = gson.fromJson(jr, PointsJson.class);
		this.callback.onDone(json);
	} catch (final Exception e) {
		this.callback.onError(e);
	} finally {
		IOUtils.closeQuietly(jr);
	}
}
 
開發者ID:Team-Fruit,項目名稱:EEWReciever,代碼行數:17,代碼來源:SeismicObservationPoints.java

示例6: sendPost

public String sendPost(String url, List<NameValuePair> fields ) throws Exception {
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(fields, Consts.UTF_8);
      HttpPost httpPost = new HttpPost(baseUrl + url);
      if(verbose) {
       System.out.println( "POST from " + address + " to " + httpPost.getURI() );
       System.out.println( "   " + fields );
      }
      httpPost.addHeader("X-Forwarded-For", address );
      httpPost.setEntity(entity);
      
      watch.reset();
      watch.start();
      CloseableHttpResponse response = httpclient.execute(httpPost);
      String content = EntityUtils.toString(response.getEntity());
      watch.stop();
      long elapsed = watch.getTime();
      checkHighestLowest(elapsed);
totalScanTime += elapsed;
      response.close();
      if(verbose) {
       System.out.println( "   " + response.getStatusLine() );
       System.out.println();
      }
      requestCount++;
      return content;
  }
 
開發者ID:Contrast-Security-OSS,項目名稱:sheepdog,代碼行數:26,代碼來源:AttackThread.java

示例7: urlRequest

/**
 * @param url 請求URL
 * @param method 請求URL
 * @param param	json參數(post|put)
 * @param auth	認證(username+:+password)
 * @return 返回結果
 */
public static String urlRequest(String url,String method,String param,String auth){
	String result = null;
	try {
		HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
		connection.setConnectTimeout(60*1000);
		connection.setRequestMethod(method.toUpperCase());
		if(auth!=null&&!"".equals(auth)){
			String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
			connection.setRequestProperty("Authorization", authorization);
		}
		if(param!=null&&!"".equals(param)){
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.write(param.getBytes(Consts.UTF_8));
			dos.flush();
			dos.close();
		}else{
			connection.connect();
		}
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK||connection.getResponseCode()==HttpURLConnection.HTTP_CREATED){
			InputStream in = connection.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=in.read(buff, 0, buff.length))>0){
				out.write(buff, 0, len);
			}
			byte[] data = out.toByteArray();
			in.close();
			result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
		}else{
			result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
		}
		connection.disconnect();
	}catch (Exception e) {
		logger.error("--http request error !",e);
	}
	return result;
}
 
開發者ID:dev-share,項目名稱:css-elasticsearch,代碼行數:48,代碼來源:HttpUtil.java

示例8: makeRequest

private String makeRequest(String endpoint, String uri, String requestType) {
    try {
        HttpPost httpPost = new HttpPost(endpoint);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("url", uri));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);

        String result = null;
        String entities = EntityUtils.toString(response.getEntity());
        JsonNode rootNode = new ObjectMapper().readTree(entities).get(requestType);

        switch (requestType) {
            case "similarEntities":
            case "relatedEntities":
                int count = 0;
                result = "";
                for (JsonNode node : rootNode) {
                    count++;
                    if (count <= ResponseData.MAX_DATA_SIZE) {
                        result += "<" + node.get("url").getTextValue() + "> ";
                    }
                    else {
                        break;
                    }
                }
                break;
            case "summary":
                result = rootNode.getTextValue();
                break;
        }
        return result.trim();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
開發者ID:dbpedia,項目名稱:chatbot,代碼行數:40,代碼來源:GenesisService.java

示例9: execute

@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String postEntity) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  if (postEntity != null) {
    StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
    httpPost.setEntity(entity);
  }

  try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    if (responseContent.isEmpty()) {
      throw new WxErrorException(
          WxError.newBuilder().setErrorCode(9999).setErrorMsg("無響應內容")
              .build());
    }

    if (responseContent.startsWith("<xml>")) {
      //xml格式輸出直接返回
      return responseContent;
    }

    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  } finally {
    httpPost.releaseConnection();
  }
}
 
開發者ID:11590692,項目名稱:Wechat-Group,代碼行數:35,代碼來源:SimplePostRequestExecutor.java

示例10: urlRequest

/**
 * @param url 請求URL
 * @param method 請求URL
 * @param param	json參數(post|put)
 * @return
 */
public static String urlRequest(String url,String method,String param,String auth){
	String result = null;
	try {
		HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
		connection.setConnectTimeout(60*1000);
		connection.setRequestMethod(method.toUpperCase());
		if(auth!=null&&!"".equals(auth)){
			String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
			connection.setRequestProperty("Authorization", authorization);
		}
		if(param!=null&&!"".equals(param)){
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.write(param.getBytes(Consts.UTF_8));
			dos.flush();
			dos.close();
		}else{
			connection.connect();
		}
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
			InputStream in = connection.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=in.read(buff, 0, buff.length))>0){
				out.write(buff, 0, len);
			}
			byte[] data = out.toByteArray();
			in.close();
			result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
		}else{
			result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
		}
		connection.disconnect();
	}catch (Exception e) {
		logger.error("--http request error !",e);
	}
	return result;
}
 
開發者ID:dev-share,項目名稱:database-transform-tool,代碼行數:47,代碼來源:HttpUtil.java

示例11: execute

@Override
public String execute(String uri, String postEntity) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }

  if (postEntity != null) {
    StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
    httpPost.setEntity(entity);
  }

  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    if (responseContent.isEmpty()) {
      throw new WxErrorException(WxError.builder().errorCode(9999).errorMsg("無響應內容").build());
    }

    if (responseContent.startsWith("<xml>")) {
      //xml格式輸出直接返回
      return responseContent;
    }

    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  } finally {
    httpPost.releaseConnection();
  }
}
 
開發者ID:binarywang,項目名稱:weixin-java-tools,代碼行數:33,代碼來源:ApacheSimplePostRequestExecutor.java

示例12: execute

@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String postEntity) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  if (postEntity != null) {
    StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
    httpPost.setEntity(entity);
  }

  CloseableHttpResponse response = null;
  try {
    response = httpclient.execute(httpPost);
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    if (responseContent.isEmpty()) {
      throw new WxErrorException(WxError.newBuilder().setErrorCode(9999).setErrorMsg("無響應內容")
              .build());
    }

    if (responseContent.startsWith("<xml>")) {
      //xml格式輸出直接返回
      return responseContent;
    }

    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  } finally {
    IOUtils.closeQuietly(response);
    httpPost.releaseConnection();
  }
}
 
開發者ID:binarywang,項目名稱:weixin-java-tools-for-JDK6,代碼行數:37,代碼來源:SimplePostRequestExecutor.java

示例13: sendShortMessage

public static void sendShortMessage() throws Exception {
	/**
	//http://www.smschinese.cn/
	HttpHeaders headers = new HttpHeaders();
	MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE);
	headers.setContentType(type);
	JSONObject jo = new JSONObject();
	jo.put("Uid", "本站用戶名");
	jo.put("Key", "接口安全秘鑰");
	jo.put("smsMob", "手機號碼");
	jo.put("smsText", "發送內容");
	HttpEntity<String> formEntity = new HttpEntity<String>(jo.toString(), headers);
	String receive = new RestTemplate().postForObject("http://utf8.sms.webchinese.cn", formEntity, String.class);
	System.out.println(receive);
	*/
	List<NameValuePair> list = new ArrayList<>();
	list.add(new BasicNameValuePair("func", "sendsms"));
	list.add(new BasicNameValuePair("username", "登錄賬號"));
	list.add(new BasicNameValuePair("password", "登錄密碼"));
	list.add(new BasicNameValuePair("mobiles", "手機號碼"));
	list.add(new BasicNameValuePair("message", "發送內容"));
	list.add(new BasicNameValuePair("extno", ""));
	HttpPost post = new HttpPost("http://sms.c8686.com/Api/BayouSmsApiEx.aspx");
	UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
	post.setEntity(urlEncodedFormEntity);
	HttpResponse httpResponse = HttpClientBuilder.create().build().execute(post);
	//短信服務器返回的信息
	String receive = EntityUtils.toString(httpResponse.getEntity());
	System.out.println(receive);
}
 
開發者ID:tank2140896,項目名稱:JavaWeb,代碼行數:30,代碼來源:MessageSendUtil.java

示例14: httpClientForPost

public static HttpResponse httpClientForPost(String url,String ip,List<NameValuePair> list,CloseableHttpClient closeableHttpClient) throws Exception {
HttpPost post = new HttpPost(url);
post.addHeader("x-forwarded-for", ip);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
post.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = closeableHttpClient.execute(post);
return httpResponse;
  }
 
開發者ID:tank2140896,項目名稱:JavaWeb,代碼行數:8,代碼來源:HttpGetPostRequestMokUtil.java

示例15: sendPostByJson

/**
    * 發送HTTP_POST請求,json格式數據
    * @param url
    * @param body
    * @return
    * @throws Exception
    */
   public static String sendPostByJson(String url, String body) throws Exception {
	CloseableHttpClient httpclient = HttpClients.custom().build();
	HttpPost post = null;
	String resData = null;
	CloseableHttpResponse result = null;
	try {
		post = new HttpPost(url);
		HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
		post.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build());
		post.setHeader("Content-Type", "application/json");
		post.setEntity(entity2);
		result = httpclient.execute(post);
		if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
			resData = EntityUtils.toString(result.getEntity());
		}
	} finally {
		if (result != null) {
			result.close();
		}
		if (post != null) {
			post.releaseConnection();
		}
		httpclient.close();
	}
	return resData;
}
 
開發者ID:xiaomin0322,項目名稱:alimama,代碼行數:33,代碼來源:HttpClientUtil.java


注:本文中的org.apache.http.Consts.UTF_8屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。