I have the following code:
public class SendRequest {
public static void main(String[] args) throws ClientProtocolException, IOException {
String url = "http://backoffice.xyz";
HttpHost proxy = new HttpHost("proxy.proxy", 8080, "http");
HttpClient client = HttpClientBuilder.create().setProxy(proxy).build();
HttpGet request = new HttpGet(url);
//request.addHeader("User-Agent", "USER-AGENT");
HttpResponse response = client.execute(request);
System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while((line = rd.readLine()) != null){
result.append(line);
}
System.out.println(result.toString());
}
}
This is returning a 407 Unauthorized Access/Cache Access Denied Error. What code do i need to include so i can authenticate through the proxy?
Does your proxy require username/password based authentication? If so, try implementing java.net.Authenticator. I guess you will need to set useSystemProperties
Authenticator.setDefault(new Authenticator(){
PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
You might need to add setDefaultCredentialsProvider(CredentialsProvider credentialsProvider) to the HTTPClientBuilder and use SystemDefaultCredentialsProvider instance for that.
1.Can you check your proxy ?? I'm not sure if proxy.proxy is correct.
Your rest of the code seems fine.
2.And also make sure you are updating httpcore version to 4.4 or above. And also you can update httpcore to latest version.
3.You could check the authentication of your proxy as #Goutham mentioned
Hope this helps!!
Related
I would like to test my web service using Junit. Once we missed the public modifier and it failed. So, to avoid such issue in the earlier stage we would like to write Junit test cases to test the web service connection.
I tried this but did not work.
String url = "http://localhost:port/webservice/path";
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet( url );
request.setHeader("username", "user1");
HttpResponse httpResponse =
HttpClientBuilder.create().build().execute(request);
HttpResponse response = client.execute(request);
httpResponse.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
while ((line = rd.readLine()) != null) {
result.append(line);
}
My web service will be like this
#Path("/path")
public interface WebServiceTest
{
//list of services
}
I should get to know whether my call is success or failure through Junit test case.
How to implement it? Any other suggestions other than Junit but It should be through Java (No Mockito)?
EDIT: I need this for both SOAP and REST web services.
Try to use RestAssured. Using a method like this and pass the appropriate values.
public static ResponseBody callAPI(String host, String body, String path, String method, Map<String,String> headers){
RequestSpecBuilder requestSpecBuilder = new RequestSpecBuilder();
requestSpecBuilder.addHeaders(headers);
requestSpecBuilder.setBody(body);
requestSpecBuilder.setBaseUri(host);
RequestSpecification requetSpecification = requestSpecBuilder.build();
requestSpecBuilder.setContentType(ContentType.JSON);
Response rs = null;
if(method.equals("DELETE")){
rs = RestAssured.given(requetSpecification).when().log().all().delete(path);
}else if(method.equals("POST")){
rs = RestAssured.given(requetSpecification).when().log().all().post(path);
}
return rs.getBody();
}
Somehow Fiddler doesn't capture the posts I send from my HttpClient provided by Apache.
But when I send the same post in C# using the HttpClient to the same server, Fiddler does intercept the sessions.
My Java code:
private DefaultHttpClient client = new DefaultHttpClient();
private HttpContext context = new BasicHttpContext();
private BasicCookieStore store = new BasicCookieStore();
public Client() throws URISyntaxException {
context.setAttribute(ClientContext.COOKIE_STORE, store);
logIn();
}
private void logIn() throws URISyntaxException {
HttpUriRequest login = RequestBuilder.post()
.setUri(new URI("http://www.derpforum.nl"))
.addParameter("username", "Kattoor4")
.addParameter("password", "XXXX")
.addHeader("Referer", "http://www.derpforum.nl/")
.build();
try (CloseableHttpResponse response = client.execute(login, context)) {
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
Any thoughts? Thanks!
I am usring Apache HttpClient(4.5.5), SWT4 and Fiddler4, and the VM arguments method does not work for me.
So I set the proxy settings in the code and it works.
HttpHost proxy = new HttpHost("localhost", 8888, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
You probably need to configure Java to use Fiddler as a proxy either in code or by setting the relevant Java system properties as below. See this question.
-Dhttp.proxyHost=127.0.0.1
-Dhttp.proxyPort=8888
My requirement is to upload the images to server using a Multipart request. I was able to create a Multipart Http Request using the HttpClient, which is deprecated. Is it possible to achieve the same using HttpUrlConnection? If yes, how?
Update:
Current code
{
ProgressDialog progress_dialog;
#Override
protected void onPreExecute() {
// setting progress bar to zero
progress_dialog=new ProgressDialog(CreateAlbum.this);
progress_dialog.setTitle("Loading..");
progress_dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.42:8080/test/fileUpload.php");
try
{
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File sourceFile = new File(fileUri);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
Log.i("RAE", "STATUS CODE IS"+statusCode);
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e("RAE", "Response from server: " + result);
progress_dialog.dismiss();
// showing the server response in an alert dialog
Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
}
AndroidHttpClient has been depreciated and has no longer support from the developers. So one will have to use java's own HttpURLConnection under java.net package. Here is a demo android application which implements HttpURLConnection. Just use the following git commands and run the application in android studio
Clone the git project :-
git clone https://github.com/viper-pranish/android-tutorial.git
Download the right version of project where HttpURLConnection is implemented
git checkout 399e3d1f9624353e522faf350f38a12db635c09a
EDIT
After you understand from my code how to make a POST with HttpUrlConnection, you can edit it and integrate the following answers: Sending files using POST with HttpURLConnection
This is how I make a form-encoded POST:
// Connection
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);
// Data to be sent
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(printParams(params));
out.flush();
out.close();
// Print received response
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
where printParams is a simple function to trasform a Map into a string like a=b&c=d:
public static String printParams(Map<String, String> params) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> e: params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(e.getKey()).append('=').append(e.getValue());
}
return sb.toString();
}
This link has everything you need to send a file to server using multipart. It has been updated to use the most recent http classes in android. I have tested it and use it myself today. Cheers!
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
For the nexts post show your code, the programmers need see that for give more great help, thanks. On the one hand I always use in my apps httpClient and it's the best way for me because you can configuration a specific client with handling cookies, authentication, connection management, and other features, it's simple if you have the code. If you want to see more info from this theme you can visit this links, in Class Overview part:
http://developer.android.com/reference/org/apache/http/client/HttpClient.html
http://developer.android.com/reference/java/net/HttpURLConnection.html
On the other hand, if you want to do a multiple connections with your server I recommend a parallel programming with httpClient with processes and threads can read more info here: http://developer.android.com/guide/components/processes-and-threads.html
// Last Update //
Sorry Rahul Batra I work with API 21... I noted this for next version of my app. But as the first Step I will try to use a backgroud tasks with httpURLConnection.
This post have a really great information:
http://android-developers.blogspot.com.es/2011/09/androids-http-clients.html
I hope it help you this answer!! If you need more information or anything let me know, good luck Rahul Batra.
When trying to get account balance used api I got an exception:
IOException: Server returned HTTP response code: 401 for URL:
https://api.pinnaclesports.com/v1/client/balance
Here's the code:
public void getBalance() throws Exception{
byte[] bytes = "username:password".getBytes("UTF-8");
String encoded = Base64.encodeBase64String(bytes);
System.out.println(encoded);
URL api = new URL("https://api.pinnaclesports.com/v1/client/balance");
URLConnection apiConnection = api.openConnection();
apiConnection.addRequestProperty("Authorization", "Basic "+encoded);
BufferedReader in = new BufferedReader(new InputStreamReader(apiConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
I think your authentication is broken or not set properly. The API uses Basic Auth and a Base64 encoded username/password pair. You should read http://www.pinnaclesports.com/en/api/manual#authentication and make sure that your authorization is correct.
Here's an explanation for HTTP status code 401:
Similar to 403 Forbidden, but specifically for use when authentication
is possible but has failed or not yet been provided. The response
must include a WWW-Authenticate header field containing a challenge
applicable to the requested resource.
Try using an Authenticator, like this:
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
});
URL api = new URL("https://api.pinnaclesports.com/v1/client/balance");
BufferedReader in = new BufferedReader(new InputStreamReader(api.openStream()));
Or if that doesn't work, then try using an HttpURLConnection instead of URLConnection,
like this:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encoded);
You might also find this related post helpful, using Apache Commons.
I am writing a client for Restful web services.
public static void main(String[] args){
// Use apache commons-httpclient to create the request/response
HttpClient client = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("aaa", "cdefg");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
GetMethod method = new GetMethod(
"http://localhost:8080/userService/usersByID/1234");
try {
client.executeMethod(method);
InputStream in = method.getResponseBodyAsStream();
// Use dom4j to parse the response and print nicely to the output stream
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
I am getting unauthorized error 401. When I checked the server logs. I found the following.
ERROR httpclient.HttpMethodDirector - Credentials cannot be used for NTLM authentication: org.apache.commons.httpclient.UsernamePasswordCredentials
So, I understood that I need to use NTLM authentication for this.
Can some one tell me how to modify this to do NTLM authentication.
Thanks in Advance.
Please check the below links
http://hc.apache.org/httpclient-3.x/authentication.html#NTLM
http://davenport.sourceforge.net/ntlm.html
Instead of setCredentials try using setProxyCredentials.
client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);