1.1.27. fejezet, HttpClient

	public static JsonObject sendPostRequestWithHttpClient(String urlString, String accessToken, String body) throws Exception {
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(urlString);
		post.setHeader("Content-Type", "application/json");
		post.setHeader("Authorization", "Bearer " + accessToken);
		post.setHeader("cache-control", "no-cache");
		post.setHeader("x-li-format", "json");
		post.setHeader("X-Restli-Protocol-Version", "2.0.0");
		StringEntity requestEntity = new StringEntity(body, "UTF-8");
		post.setEntity(requestEntity);
		HttpResponse response = client.execute(post);
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity, "UTF-8");
		JsonReader jsonReader = Json.createReader(new StringReader(responseString.toString()));
		JsonObject jsonObject = jsonReader.readObject();
 
		return jsonObject;
	}

Küldés form formában

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
 
public class Homework4HttpPost {
 
	public static void main(String[] args) {
        String url = "http://192.168.1.139:5000/clipboard/post";
        String clipboardContent = "teszt";
        Integer result;
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
 
            // Form based params
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("content", clipboardContent));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
 
            /* JSON request body
            JSONObject json = new JSONObject();
            json.put("content", clipboardContent);
 
            StringEntity requestEntity = new StringEntity(json.toString(),
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);
            */
 
            CloseableHttpResponse response = client.execute(httpPost);
            result = response.getStatusLine().getStatusCode();
            System.out.println(result);
            client.close();
 
        } catch (Exception e) {
            result = 500;
        } finally {
        }
	}
 
}

Kapcsolódó hivatkozások