I am not able to get a response from eclipse when integrated in java code. I am able to retrieve the response from postman/insomnia, but not from eclipse. I masked the token and the URL in this image.
My current code is:
public class Test{
public static void main(String[] args) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
httppost.addHeader("Authorization", "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
httppost.addHeader("Accept", "*/*");
httppost.addHeader("Content-type", "multipart/form-data; boundary=X-INSOMNIA-BOUNDARY");
httppost.addHeader("Host","process-workorders-mti64mke4a-uc.a.run.app");
File fileToUse = new File("D:\\firstImage.jpg"); // this is the image I am uoploadin
FileBody data = new FileBody(fileToUse);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("mode", new StringBody("api"));
reqEntity.addPart("file", data);
*// seems there is issue here in passing form parameters*
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
System.out.println( response ) ;
HttpEntity resEntity = response.getEntity();
System.out.println( resEntity ) ;
System.out.println( EntityUtils.toString(resEntity) );
EntityUtils.consume(resEntity);
httpclient.getConnectionManager().shutdown();
}
}
Below are the imports:
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
Tried OKHTTPClient and it worked
Related
I would like to create a URI using apache class org.apache.http.client.utils.URIBuilder and I need to not encode query params to percent-encoding.
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.net.URI;
public class Main {
public static void main(String[] args) throws Exception {
RequestConfig config = RequestConfig.custom().build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(config);
// URI url = new URI("http://some-website.com/?range=10,20");
// If url is created with the line above the comma "," is not encoded when sending the request
// When you use URIBuilder the comma "," is converted to "%2C"
URIBuilder uribuilder = new URIBuilder("http://some-website.com/");
uribuilder.addParameter("range", "10,20");
URI url = uribuilder.build();
System.out.println("URL => " + url.toString());
HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getScheme());
HttpClient client = builder.build();
HttpRequestBase req = new HttpPost(url);
HttpResponse httpResponse = client.execute(targetHost, req);
HttpEntity entity = httpResponse.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
System.out.println("Finished");
}
}
Is there a way to do that using the URIBuilder class like some flag I don't know?
I would appreciate other suggests (maybe better ways than my code) to accomplish this. But I can't send the characters in query string encoded.
Thanks in advance.
I have been able to successfully authentication to a service that requires ntlm authentication when using the WinHttpClients and a GET request. However when I try to do a POST I always get a 401 return code. Has anyone done this sucessfully before?
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.WinHttpClients;
public class WindowsAuthPOst {
public static void main (String []args) throws Exception, IOException
{
org.apache.log4j.BasicConfigurator.configure();
CloseableHttpClient httpclient = WinHttpClients.createDefault();
HttpHost target = new HttpHost("SomeHost.domain", 443, "https");
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("/some/Service.svc");
CloseableHttpResponse response1 = httpclient.execute(target, httpget, context);
try {
HttpEntity entity1 = response1.getEntity();
} finally {
response1.close();
}
// Execute an expensive method next reusing the same context (and connection)
HttpPost httppost = new HttpPost("/some/Service.svc");
httppost.setHeader("SOAPAction", "Some Soap Action");
httppost.setEntity(new StringEntity("Soap Payload"));
CloseableHttpResponse response2 = httpclient.execute(target, httppost, context);
try {
HttpEntity entity2 = response2.getEntity();
} finally {
response2.close();
}
}
}
You can check if it is available with.
if (!WinHttpClients.isWinAuthAvailable()) {
System.out.println("Integrated Win auth is not supported!!!");
}
If not, it could be that you do not have jna.jar in your classpath. It depends on jna and will silently return false on the above if it not there, see source code.
Try with get (or options) before post. Some webservers requires that because of CORS.
https://stackoverflow.com/a/38410411/2376661
I am trying to execute a multipart request using the below function, but when I create the httpClient I get this exception:
E/AndroidRuntime(8909): Caused by: java.lang.NoSuchFieldError:
org.apache.http.message.BasicLineFormatter.INSTANCE
I am using httpclient-4.3.4 (imports are below as well)
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public static void uploadFile() throws ClientProtocolException, IOException {
String filepath = Environment.getExternalStorageDirectory() + "/Download/img.jpg";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("ip/myRestservice");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
File file = new File(filepath);
builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "file.ext");
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
}
How to solve it?
I am tring to perform Digest Authentication using the HttpClient library, but I keep getting: HTTP/1.1 401 Unauthorized.
When I try the request from Firefox it works fine and I get a response correctly, so I know the server authentication is working fine.
Update: moved Working code to answer.
The following code worked for me
import java.util.Random;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against a
* target site that requires user authentication.
*/
public class RestClient {
public static void main(String args[]) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 8001, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
final String userName = "admin";
final String password = "password";
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8001),
new UsernamePasswordCredentials(userName, password));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local
// auth cache
DigestScheme digestAuth = new DigestScheme();
// Suppose we already know the realm name
digestAuth.overrideParamter("realm", "some realm");
// Suppose we already know the expected nonce value
digestAuth.overrideParamter("nonce", "whatever");
authCache.put(targetHost, digestAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("http://localhost:8001/rest/test");
try {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
I would like to POST (in Java) a multipart/mixed request, where one part is of type 'application/json' and the other of type 'application/pdf'. Does anyone know of a library which will allow me to do this easily? Surprisingly I haven't been able to find one.
I'll generate the JSON, but I need to be able to set the content type of that part to 'application/json'.
Many thanks,
Daniel
Easy, use the Apache Http-client library (this code used version 4.1 and the jars httpclient, httpcore and httpmime), here's a sample:
package com.officedrop.uploader;
import java.io.File;
import java.net.URL;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class SampleUploader {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
String basePath = "http://localhost/";
URL url = new URL( basePath );
HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
HttpPost httpost = new HttpPost( String.format( "%s%s", basePath, "ze/api/documents.xml"));
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file_1", new FileBody( new File( "path-to-file.pdf" ) , "file.pdf", "application/pdf", null));
entity.addPart("uploaded_data_1", new FileBody( new File( "path-to-file.json" ) , "file.json", "application/json", null));
httpost.setEntity(entity);
HttpResponse response = httpclient.execute( targetHost, httpost);
}
}