Im doing a REST server and client using java to learn.
Everything works ok but the PUT request from the client dont pass the data in the body correctly because when I see the log in the server the parameters are NULL
This is the client PUT request code:
private static class Mod {
int idUser;
String nameUser;
String passwordUser;
public Mod(int idUser, String nameUser, String passwordUser) {
this.idUser = idUser;
this.nameUser = nameUser;
this.passwordUser = passwordUser;
try {
URL url = new URL("http://localhost:8080/api/users/" + idUser + "/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setDoInput(true);
connection.setDoOutput(true);
HashMap<String, String> postDataParams = new HashMap<>();
postDataParams.put("nameUser", this.nameUser);
postDataParams.put("passwordUser", this.passwordUser);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
writer.write(getPutDataString(postDataParams));
writer.flush();
writer.close();
os.close();
if (connection.getResponseCode() == 201) {
System.out.println("Modified");
connection.disconnect();
} else {
System.out.println("Error");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private String getPutDataString(HashMap<String, String> params) {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first) {
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}
return result.toString();
}
}
This is the code for the POST request. It uses the same way of "injecting" the parameters and works perfect:
private static class Create {
String nameUser, passwordUser;
public Create(String nameUser, String passwordUser) {
this.nameUser = nameUser;
this.passwordUser = passwordUser;
try {
URL url = new URL("http://localhost:8080/api/users/");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setRequestMethod("POST");
HashMap<String, String> postDataParams = new HashMap<>();
postDataParams.put("nameUser", this.nameUser);
postDataParams.put("passwordUser", this.passwordUser);
myConnection.setDoInput(true);
myConnection.setDoOutput(true);
OutputStream os = myConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
myConnection.getResponseCode();
if (myConnection.getResponseCode() == 201) {
System.out.println("Created");
myConnection.disconnect();
} else {
System.out.println("Error");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private String getPostDataString(HashMap<String, String> params) {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first) {
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}
return result.toString();
}
}
The REST Controller in the server:
#RestController
#RequestMapping("/api")
public class UserRestController {
#Autowired
private IUserService userService;
#GetMapping("/users")
public List<User> index() {
return userService.findAll();
}
#GetMapping("/users/{id}")
public User show(#PathVariable Long id) {
return this.userService.findById(id);
}
#PostMapping("/users")
#ResponseStatus(HttpStatus.CREATED)
public User create(#ModelAttribute User user) {
this.userService.save(user);
return user;
}
#PutMapping("/users/{id}")
#ResponseStatus(HttpStatus.CREATED)
public User update(#ModelAttribute User user, #PathVariable Long id) {
User currentUser = this.userService.findById(id);
currentUser.setNameUser(user.getNameUser());
currentUser.setPasswordUser(user.getPasswordUser());
this.userService.save(currentUser);
return currentUser;
}
#DeleteMapping("/users/{id}")
#ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(#PathVariable Long id) {
this.userService.delete(id);
}
}
You should use x-www-form-urlencoded because you are not sending any file.
Moreover, you need more work to manually do a form-data request so it's better to change the server so that it accepts x-www-form-urlencoded parameters.
After you have modified the server, add the content type to the request:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
and remove this line:
connection.setDoInput(true)
because you use the HttpURLConnection as output.
Note that you can make the PUT request easily with Apache HttpClient.
Related
I have been working on my own Http Client Class, and i want a way to implement the onload and oerror feature like, "declaring an event and actions for that event", if an error with the connection happened i must have the ability to specify a custom action for it.
public static void Error(int code){
System.out.println("Oops, something went wrong Error code:" + code.toString());
}
URL url = new URL("http://example.com/");
Map<String, String> params = new HashMap<String, String>();
params.put("key","value");
http_client client = new http_client(url, "GET", params , true);
client.onError = Error(client.ErrorCode);
Something like that.
Here is my class:
class http_client {
protected String responseText;
protected boolean loaded = false;
protected boolean error = false;
public http_client(URL url, String method , Map<String,String> parameters , boolean cache) throws IOException, ProtocolException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status > 299){
error = true;
}
connection.setRequestMethod(method);
if(method == "POST"){
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
connection.setUseCaches(cache);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream s = new DataOutputStream(connection.getOutputStream());
s.writeBytes(paramToStr(parameters));
s.flush();
s.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String CurrentLine;
int lines = 0;
while((CurrentLine = reader.readLine()) != null){
lines += 1;
response.append(CurrentLine + "\n");
}
reader.close();
responseText = response.toString();
responseText = responseText.substring(0 , responseText.length() - 1);
if(lines == 1){
responseText = responseText.replace("\n","");
}
loaded = true;
}
public static String paramToStr(Map<String, String> parameters) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
result.append("?");
for(Map.Entry<String,String> entry: parameters.entrySet()){
String key = URLEncoder.encode(entry.getKey() , "UTF-8");
String value = URLEncoder.encode(entry.getValue() , "UTF-8");
result.append(key);
result.append("=");
result.append(value);
result.append("&");
}
String str = result.toString();
str = result.substring(0 , str.length() - 1);
return str;
}
}
Thanks in advance.
You can use the Function Interface Java provides:
class http_client {
protected String responseText;
protected boolean loaded = false;
protected Function<Integer, Void> success;
protected Function<Integer, Void> error;
public http_client(URL url, String method , Map<String,String> parameters , boolean cache, Function<Integer, String>success, Function<Integer, String> error) throws IOException, ProtocolException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status > 299){
error.apply(status);
} else {
success.apply(status);
}
...
}
}
to call it just pass some lambda function
...
http_client client = new http_client(url, "GET", params , true, status -> System.out.println("success! " + status), status -> System.out.println("error " + status));
I am trying to fetch the application only bearer token by using my consumer key and consumer secret following this. This is my implementation:
public class OAuthApplicationOnlyBearerTokenFetchTask extends AsyncTask<String, Void, String> {
private static Logger logger =
Logger.getLogger(OAuthApplicationOnlyBearerTokenFetchTask.class.getName());
final static String URL_TWITTER_OAUTH2_TOKEN = "https://api.twitter.com/oauth2/token";
final static String USER_AGENT = "TwitterMotion User Agent";
protected String mApplicationOnlyBearerToken;
#Override
protected String doInBackground(String... tokens) {
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
String encodedCredentials = encodeKeysFrom(consumerKey, consumerSecret);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(URL_TWITTER_OAUTH2_TOKEN);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Host", "api.twitter.com");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
urlConnection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
urlConnection.setRequestProperty("Content-Length", "29");
urlConnection.setUseCaches(false);
writeRequest(urlConnection, "grant_type=client_credentials");
String jsonResponse = readResponse(urlConnection);
logger.log(INFO, "jsonResponse of the bearer oauth request: ", jsonResponse);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
logger.log(Level.SEVERE, "HTTP 403 (Forbidden) returned from Twitter API call for bearer token. " +
"Check values of Consumer Key and Consumer Secret in tokens.properties");
throw new RejectedAuthorizationException(urlConnection.getResponseCode(), "HTTP 403 (Forbidden) returned attempting to get Twitter API bearer token");
}
JSONObject jsonResponseObject = new JSONObject(jsonResponse);
if (jsonResponseObject != null) {
mApplicationOnlyBearerToken = (String) jsonResponseObject.get("access_token");
} else {
// TODO
}
return mApplicationOnlyBearerToken;
} catch (Exception ex) {
logger.log(Level.SEVERE, "", ex);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(String applicationOnlyBearerToken) {
this.mApplicationOnlyBearerToken = applicationOnlyBearerToken;
}
public String getApplicationOnlyBearerToken() {
return mApplicationOnlyBearerToken;
}
private String encodeKeysFrom(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String combinedEncodedKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encode(combinedEncodedKey.getBytes(), Base64.NO_WRAP);
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
// TODO
return null;
}
}
private boolean writeRequest(HttpURLConnection connection, String requestBody)
throws IOException {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(connection.getOutputStream()));
bufferedWriter.write(requestBody);
bufferedWriter.flush();
return true;
}
catch (IOException ex) {
return false;
}
finally {
if (bufferedWriter != null) {
bufferedWriter.close();
}
}
}
private String readResponse(HttpURLConnection connection) throws IOException {
BufferedReader bufferedReader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + System.getProperty("line.separator"));
}
return stringBuilder.toString();
}
catch (IOException e) {
return null;
}
finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
}
}
But I am getting HTTP 403 Forbidden.
I also added permission on manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I can not understand what is the issue actually. Thanks in advance!
Never mind, I've found the bug.
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
It should be
String consumerSecret = tokens[1];
I have an Web Application with Spring Security Framework and running on Tomcat 8. Now, I am facing a new problem to create android app which support user sessions without cookies. I tried to find some documentation like this and i tried it with using HttpUrlConnection ( I don't know which one is more better with other ), this is my failure code.
public static String jsessionid = SessionIdentifierGenerator.nextSessionId();
public static String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
Log.d("url = ",requestURL);
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(45000);
conn.setConnectTimeout(45000);
conn.setRequestMethod("POST");
Log.d("Cookie : ", jsessionid);
conn.setRequestProperty("Cookie","JSESSIONID=" + SessionIdentifierGenerator.nextSessionId());
conn.setDoInput(true);
conn.setDoOutput(true);
// conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
int responseCode=conn.getResponseCode();
writer.close();
os.close();
System.out.println(".toString() = "+responseCode);
System.out.println(".HttpsURLConnection.HTTP_OK = "+HttpsURLConnection.HTTP_OK);
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
Log.d("entry.getKey() = ",entry.getKey());
Log.d("entry.getValue() = ",entry.getValue());
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
System.out.println("tetstes = "+result.toString());
return result.toString();
}
this methode for create a new session.
public final class SessionIdentifierGenerator {
private static SecureRandom random = new SecureRandom();
public static String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}
HashMap<String, String> parameter = new HashMap<String, String>();
parameter.put("username", username);
parameter.put("password", password);
and the last i call this performPostCall("http://localhost:8080/login/authenticate?spring-security-redirect=/login/ajaxSuccess", parameter);
I'm working on an API and I am experiencing a strange thing. When I make an API request from which I receive a JSON response. In the browser I receive the following JSON:
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{
"Reason":"sfdfsdf",
"Date":"2016-10-02",
"SlotId":"1"
}
]
}]
But I receive a different JSON response on my Android device.
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{"Reason":"sfdfsdf","Date":"2016-10-02","SlotId":"1"
}
]
}]
This is the class I'm using to make that Request
public class NewPost extends AsyncTask<String, Integer, String> {
private final Context context;
private final Registerinterface inter;
private int response_code = 0;
private HashMap<String, String> postDataParams;
private ProgressDialog prgDialog;
public NewPost(Context c, Registerinterface inter, HashMap<String, String> postParamater) {
context = c;
this.inter = inter;
this.postDataParams = postParamater;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!new NetworkStatus(context).isNetworkAvailable()) {
inter.Result("", Constants.No_Internet);
this.cancel(true);
} else {
prgDialog = new ProgressDialog(new ContextThemeWrapper(context, android.R.style.Theme_DeviceDefault_Light_Dialog));
prgDialog.setMessage("Loading...");
prgDialog.show();
prgDialog.setIndeterminate(false);
}
}
#Override
protected String doInBackground(String... param) {
URL url;
String response = "";
try {
url = new URL(param[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null)
sb.append(line + "\n");
response = sb.toString();
return response;
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prgDialog.dismiss();
if (result == null || result.equals("null"))
inter.Result("null", response_code);
else
inter.Result(result, response_code);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
I've been stuck on this problem for hours, any help would be appreciated.
You can remove the from your JSON data.
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because " is not valid in a JSON object.
I am trying to build a simple HTTP client program that sends a request to a web server and prints the response out to the user.
I have got the following error when I run my code and I am not sure what is causing it:
-1
Exception in thread "main" java.lang.IllegalArgumentException: port out of range:-1
at java.net.InetSocketAddress.(InetSocketAddress.java:118)
at java.net.Socket.(Socket.java:189)
at com.example.bookstore.MyHttpClient.execute(MyHttpClient.java:18)
at com.example.bookstore.MyHttpClientApp.main(MyHttpClientApp.java:29)
Java Result: 1
Below is my MyHttpClient.java class
public class MyHttpClient {
MyHttpRequest request;
public MyHttpResponse execute(MyHttpRequest request) throws IOException {
this.request = request;
int port = request.getPort();
System.out.println(port);
//Create a socket
Socket s = new Socket(request.getHost(), request.getPort());
//Create I/O streams
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter outToServer = new PrintWriter(s.getOutputStream());
//Get method (POST OR GET) from request
String method = request.getMethod();
//Create response
MyHttpResponse response = new MyHttpResponse();
//GET Request
if(method.equalsIgnoreCase("GET")){
//Construct request line
String path = request.getPath();
String queryString = request.getQueryString();
//Send request line to server
outToServer.println("GET " + path + " HTTP/1.0");
//=================================================\\
//HTTP RESPONSE
//RESPONSE LINE
//Read response from server
String line = inFromServer.readLine();
//Get response code - should be 200.
int status = Integer.parseInt(line.substring(9, 3));
//Get text description of response code - if 200 should be OK.
String desc = line.substring(13);
//HEADER LINES
//Loop through headers until get to blank line...
//Header name: Header Value - structure
do{
line = inFromServer.readLine();
if(line != null && line.length() == 0){
//line is not blank
//header name start of line to the colon.
String name = line.substring(0, line.indexOf(": "));
//header value after the colon to end of line.
String value = String.valueOf(line.indexOf(": "));
response.addHeader(name, value);
}
}while(line != null && line.length() == 0);
//MESSAGE BODY
StringBuilder sb = new StringBuilder();
do{
line = inFromServer.readLine();
if(line != null){
sb.append((line)+"\n");
}
}while(line != null);
String body = sb.toString();
response.setBody(body);
//return response
return response;
}
//POST Request
else if(method.equalsIgnoreCase("POST")){
return response;
}
return response;
}
}
This is the MyHttpClientApp.java class
public class MyHttpClientApp {
public static void main(String[] args) {
String urlString = null;
URI uri;
MyHttpClient client;
MyHttpRequest request;
MyHttpResponse response;
try {
//==================================================================
// send GET request and print response
//==================================================================
urlString = "http://127.0.0.1/bookstore/viewBooks.php";
uri = new URI(urlString);
client = new MyHttpClient();
request = new MyHttpRequest(uri);
request.setMethod("GET");
response = client.execute(request);
System.out.println("=============================================");
System.out.println(request);
System.out.println("=============================================");
System.out.println(response);
System.out.println("=============================================");
}
catch (URISyntaxException e) {
String errorMessage = "Error parsing uri (" + urlString + "): " + e.getMessage();
System.out.println("MyHttpClientApp: " + errorMessage);
}
catch (IOException e) {
String errorMessage = "Error downloading book list: " + e.getMessage();
System.out.println("MyHttpClientApp: " + errorMessage);
}
}
}
MyHttpRequest
public class MyHttpRequest {
private URI uri;
private String method;
private Map<String, String> params;
public MyHttpRequest(URI uri) {
this.uri = uri;
this.method = null;
this.params = new HashMap<String, String>();
}
public String getHost() {
return this.uri.getHost();
}
public int getPort() {
return this.uri.getPort();
}
public String getPath() {
return this.uri.getPath();
}
public void addParameter(String name, String value) {
try {
name = URLEncoder.encode(name, "UTF-8");
value = URLEncoder.encode(value, "UTF-8");
this.params.put(name, value);
}
catch (UnsupportedEncodingException ex) {
System.out.println("URL encoding error: " + ex.getMessage());
}
}
public Map<String, String> getParameters() {
return this.params;
}
public String getQueryString() {
Map<String, String> parameters = this.getParameters();
// construct StringBuffer with name/value pairs
Set<String> names = parameters.keySet();
StringBuilder sbuf = new StringBuilder();
int i = 0;
for (String name : names) {
String value = parameters.get(name);
if (i != 0) {
sbuf.append("&");
}
sbuf.append(name);
sbuf.append("=");
sbuf.append(value);
i++;
}
return sbuf.toString();
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
#Override
public String toString() {
StringBuilder sbuf = new StringBuilder();
sbuf.append(this.getMethod());
sbuf.append(" ");
sbuf.append(this.getPath());
if (this.getMethod().equals("GET")) {
if (this.getQueryString().length() > 0) {
sbuf.append("?");
sbuf.append(this.getQueryString());
}
sbuf.append("\n");
sbuf.append("\n");
}
else if (this.getMethod().equals("POST")) {
sbuf.append("\n");
sbuf.append("\n");
sbuf.append(this.getQueryString());
sbuf.append("\n");
}
return sbuf.toString();
}
}
MyHttpResponse
public class MyHttpResponse {
private int status;
private String description;
private Map<String, String> headers;
private String body;
public MyHttpResponse() {
this.headers = new HashMap<String, String>();
}
public int getStatus() {
return this.status;
}
public void setStatus(int status) {
this.status = status;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, String> getHeaders() {
return this.headers;
}
public void addHeader(String header, String value) {
headers.put(header, value);
}
public String getBody() {
return body;
}
public void setBody(String is) {
this.body = is;
}
#Override
public String toString() {
StringBuilder sbuf = new StringBuilder();
sbuf.append("Http Response status line: ");
sbuf.append("\n");
sbuf.append(this.getStatus());
sbuf.append(" ");
sbuf.append(this.getDescription());
sbuf.append("\n");
sbuf.append("---------------------------------------------");
sbuf.append("\n");
sbuf.append("Http Response headers: ");
sbuf.append("\n");
for (String key: this.getHeaders().keySet()) {
String value = this.getHeaders().get(key);
sbuf.append(key);
sbuf.append(": ");
sbuf.append(value);
sbuf.append("\n");
}
sbuf.append("---------------------------------------------");
sbuf.append("\n");
sbuf.append("Http Response body: ");
sbuf.append("\n");
sbuf.append(this.getBody());
sbuf.append("\n");
return sbuf.toString();
}
}
Any ideas what might be happening? Many thanks in advance.
I guess your request don't specify a port explicitly and so your request.getPort() is returning -1. And then you try to connect to port -1. And this is illegal.
Instead of that, before using the port : check if it is <= 0 and in this case use 80 as default value.
int port = request.getPort();
if(port<=0) port=80;
since there is no set port in the URI, as of javadocs -1 is returned from port:
http://docs.oracle.com/javase/6/docs/api/java/net/URI.html#getPort()
The port component of this URI, or -1 if the port is undefined
Lots of recreating the wheel going on here. Why not use Java's in-built HTTP client (at least; there are also many third-party HTTP clients out there that do very nicely).
URL url = new URL("http://stackoverflow.com");
final HttpURLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.connect();
int responseCode = connection.getResponseCode();
etc.
use
uri = URIUtil.encodeQuery(urlString)
instead
uri = new URI(urlString);