Special characters such as (“ ”,') gets converted into ? while applying
interceptor in retrofit2.While getting response from retrofit2 , i am getting special characters but the interceptor changes the special character to ? and displays ? instead of special characters
Adding retrofit in Interceptor:
CustomRequestInterceptor requestInterceptor = newCustomRequestInterceptor();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY :
HttpLoggingInterceptor.Level.NONE);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(requestInterceptor);
httpClient.addInterceptor(logging);
Interceptor class(CustomRequestInterceptor.java) for retrofit2:
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
Log.i(TAG, "Response edited: " + URLDecoder.decode(newResponseString));
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
byte[] ptext = res_JsonObject.toString().getBytes(ISO_8859_1);
String value = new String(ptext, UTF_16);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), value))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}
Expected output:
{
"comment": "“hello”"
}
Actual output:
{
"comment": "?hello?"
}
The problem is in the return statement of intercept method,
when we call ResponseBody.create(), the responsebody class converts data to UTF-8 format and UTF-8 does not support characters like (“,”) so it gives us "?" sign because we have given response.body().contentType(), so it converts to UTF-8 which is default.
The solution is to not to pass response.body().contentType() to create() and give our own contentType.
Here is the updated class.
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
MediaType contentType = MediaType.parse(response.body().contentType() + "; charset=utf-32");
return response.newBuilder()
.body(ResponseBody.create(contentType, newResponseString.getBytes()))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}
Related
I have the following POST Request in SOAPUI which seams to work
so i have an endpoint a resource A Header and a Header Parameter
when i want to implement this with the RestTemplate i dont know how to add the header parameter what i tried is
public void setForward(String sessionId,String dn, String cf) {
try {
final String setForwardURL = "https://"+ getHost() + ":"+ getPort() + "/inyama/service/logicaldevice/setForwarding";
RestTemplate restTemplateSetForward = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("ClientSessionId",sessionId);
headers.setContentType(MediaType.APPLICATION_XML);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new StringHttpMessageConverter());
restTemplateSetForward.setMessageConverters(messageConverters);
String requestBodyCallForward =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<ns3:SetForwarding xmlns:ns14=\"http://calllog.common.avaya.com/\"" +
"xmlns:ns15=\"http://recording.common.avaya.com/\"" +
"xmlns:ns9=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
"xmlns:ns5=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"" +
"xmlns:ns12=\"http://conferencing.avaya.com/\" xmlns:ns6=\"http://com.avaya.inkaba.dal\"" +
"xmlns:ns13=\"http://voicemail.common.avaya.com/\"" +
"xmlns:ns7=\"http://com.avaya.inkaba.wstransfer\"" +
"xmlns:ns10=\"http://ccragent.common.avaya.com/\"" +
"xmlns:ns8=\"http://com.avaya.common.csta.extended\"" +
"xmlns:ns11=\"http://conferencing.common.avaya.com/\"" +
"xmlns:ns2=\"http://openapi.common.avaya.com/\"" +
"xmlns:ns4=\"http://schemas.xmlsoap.org/ws/2004/09/transfer\"" +
"xmlns:ns3=\"http://www.ecma-international.org/standards/ecma-323/csta/ed4\">" +
"<ns3:device" +
"typeOfNumber=\"dialingNumber\">" + dn + "</ns3:device>" +
"<ns3:forwardingType>forwardImmediate</ns3:forwardingType>" +
"<ns3:activateForward>true</ns3:activateForward>" +
"<ns3:forwardDN typeOfNumber=\"dialingNumber\">"+ cf + "</ns3:forwardDN>" +
"</ns3:SetForwarding>";
HttpEntity<String> restRequest = new HttpEntity<String>(requestBodyCallForward, headers);
final ResponseEntity<String> responseSetForward = restTemplateSetForward.postForEntity(setForwardURL, restRequest, String.class);
HttpStatus statusCallForward = responseSetForward.getStatusCode();
boolean success = statusCallForward.is2xxSuccessful();
} catch (RestClientException e) {
reporter.problemStackTrace(getClass(), e.getMessage(), e);
} catch (Exception e) {
reporter.problemStackTrace(getClass(), e.getMessage(), e);
}
}
I tried to set the header parameter with add but this does not work how can i add dies simple Header Parameter to my request
I get a estClientException Bad Request ehn i do no add my clienSessiinid i get a unauthorized access Bot th login which is almost the same works but the login ha no parameter
public String login() {
String sessionId = "";
try {
final String loginURL = "https://"+ getHost() + ":"+ getPort() + "/inyama/service/session";
String requestBody =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ns:userLoginRequest xmlns:ns=\"http://openapi.common.avaya.com/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
"<userName>" +getUserName() + "</userName>"+
"<userPassword>" + getUserPassword()+ "</userPassword>"+
"<applicationName>talkbase</applicationName>"+
"<loginSubscriptionRequest httpMethod=\"WEBSOCKET\" callBackUrl=\""+ callBackUrl() +" \">"+
"<eventTypes>CapabilityExchangeServicesCallbackEvents</eventTypes>"+
"<eventTypes>MonitoringServicesCallbackEvents</eventTypes>"+
"<eventTypes>SnapshotServicesCallbackEvents</eventTypes>"+
"<eventTypes>CallControlFeaturesEvents</eventTypes>"+
"<eventTypes>CallAssociatedFeaturesEvents</eventTypes>"+
"<eventTypes>PhysicalDeviceFeaturesEvents</eventTypes>"+
"<eventTypes>LogicalDeviceFeaturesEvents</eventTypes>"+
"<eventTypes>DeviceMaintenanceEvents</eventTypes>"+
"<eventTypes>VoicemailServicesEvents</eventTypes>"+
"<eventTypes>RecordingServicesEvents</eventTypes>"+
"<eventTypes>CallLogEvents</eventTypes>"+
"<eventTypes>DirectoryEvents</eventTypes>"+
"<eventTypes>ImEvents</eventTypes>"+
"<eventTypes>PresenceEvents</eventTypes>"+
"<eventTypes>LogoutEvents</eventTypes>"+
"</loginSubscriptionRequest>"+
"</ns:userLoginRequest>";
RestTemplate restTemplateLogin = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new StringHttpMessageConverter());
restTemplateLogin.setMessageConverters(messageConverters);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<String> restRequest = new HttpEntity<String>(requestBody, headers);
final ResponseEntity<String> responseLogin = restTemplateLogin.postForEntity(loginURL, restRequest, String.class);
HttpStatus status = responseLogin.getStatusCode();
boolean success = status.is2xxSuccessful();
if ( success ) {
if ( responseLogin.hasBody() ) {
String body = responseLogin.getBody();
sessionId = getStringElement(body,"clientSessionID");
}
}
} catch (RestClientException e) {
reporter.problemStackTrace(getClass(), e.getMessage(), e);
} catch (Exception e) {
reporter.problemStackTrace(getClass(), e.getMessage(), e);
}
return sessionId;
}
In my spring boot project I'am trying to intercept a rest api post in this way:
Rest Controller:
#Rest Controller
#RequestMapping("/")
public class FourStoreControllerInterface {
#ApiOperation(value = "Manage Multiple 4Store Post")
#ApiResponses(value = { #ApiResponse(code = 401, message = "Unauthorized"),
#ApiResponse(code = 403, message = "Forbidden") })
#PostMapping("**")
public ResponseEntity<?> manageMultiplePost4StoreWithRestTemplate(
#RequestParam #ApiParam(hidden = true) Map<String, String> allParams) throws Exception{
final String methodName = "manageMultiplePost4StoreWithRestTemplate()";
try {
startLog(methodName);
return fourStoreService.managePostEndpointsWithRestTemplate(allParams);
} catch (final Exception e) {
this.errorLog(methodName, e);
throw e;
} finally {
endLog(methodName);
}
}
}
Service:
#ResponseBody
public ResponseEntity<?> managePostEndpointsWithRestTemplate(Map<String, String> allParams) {
final String methodName = "managePostEndpointsWithRestTemplate(Map<String, String> allParams, JSONObject jsonParams)";
try {
startLog(methodName);
return managePost(allParams);
} catch (Exception e) {
logger.error(e.getMessage());
throw e;
} finally {
endLog(methodName);
}
}
managePost (method implemented in AbstractService):
public ResponseEntity<?> managePost(Map<String, String> allParams) {
try {
try {
logger.debug("I AM HERE WITH MAP");
// REQUEST 1
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
Route routeConfiguration = findRootPosts(request);
if (routeConfiguration != null) {
String url = routeConfiguration.getDestination().getProtocol()
+ routeConfiguration.getDestination().getIp() + ":"
+ routeConfiguration.getDestination().getPort() + request.getRequestURI();
boolean first = true;
for (String key : allParams.keySet()) {
logger.debug("OLD ALL PARAMETERS : {} ", key + "=" + allParams.get(key));
}
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(routeConfiguration.getDestination().getUsername(),
routeConfiguration.getDestination().getPassword());
for (String headersName : Collections.list(request.getHeaderNames())) {
List<String> headersValue = Collections.list(request.getHeaders(headersName));
headers.put(headersName, headersValue);
logger.debug(" REQUEST 1 HEADERS : {} = {} ", headersName, headersValue);
}
for (Cookie c : request.getCookies()) {
logger.debug(" REQUEST 1 COOKIES : {} = {} ", c.getName(), c.getValue());
}
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
// map.putAll(headers);
for (String key : allParams.keySet()) {
map.put(key, Arrays.asList(allParams.get(key)));
}
logger.debug("MAP OF PARAMETERS : {} ", map);
// REQUEST 2
HttpEntity<MultiValueMap<String, String>> request2;
if (allParams != null && !allParams.isEmpty())
request2 = new HttpEntity<MultiValueMap<String, String>>(map, headers);
else
request2 = new HttpEntity(headers);
logger.debug("BODY REQUEST 2: {} ", request2.getBody());
if (url.startsWith("https")) {
restTemplate = getRestTemplateForSelfSsl();
} else {
// restTemplate = new RestTemplate();
}
logger.debug("URL POST: {} ", url);
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).build(true);
ResponseEntity<?> response;
if (xssResponseFilter) {
response = restTemplate.exchange(new URI(uriComponents.toUriString()), HttpMethod.POST,
request2, String.class);
} else {
response = restTemplate.exchange(new URI(uriComponents.toUriString()), HttpMethod.POST,
request2, byte[].class);
}
HttpStatus statusCode = response.getStatusCode();
logger.debug("STATUS POST: {} ", statusCode);
HttpHeaders responseHeaders = response.getHeaders();
logger.debug("RESPONSE HEADERS : {} ", responseHeaders);
logger.debug("RESPONSE POST: {} ", response);
if (xssResponseFilter) {
response = sanitizeResponseBody((ResponseEntity<String>) response);
}
return response;
}
} catch (HttpStatusCodeException e) {
logger.error(e.getMessage());
return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsByteArray());
}
} catch (Exception e) {
logger.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Not valid route found");
}
With some POST I have no problems, in fact I get 200, and I can also see all the parameters that are present in the map that I pass in input ... with other POST I get error 400 BAD REQUEST and I notice that the map of the input parameters comes to me printed blank. How can I solve the problem?
In my opinion the problem concerns the fact that at the entrance I find myself an empty map ... what should I do in these cases?
add #RestController annotation in the rest controller class.
I need to send a json code, via the get method.
I tried to send through a JsonObjectRequest with the method, url and the parameters, the response was null and the json was not sent.
JSONObject request = new JSONObject();
try {
request.put("CodigoInicial", "1");
request.put("CodigoFinal", "2");
;
} catch (JSONException e) {
e.printStackTrace();
}
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.GET, url2,request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Log.d(TAG, response.toString() + " i am queen");
try {
JSONArray jsonArray = response.getJSONArray("LinhasClientes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
int codigo = employee.getInt("Codigo");
String Nome = employee.getString("Nome");
String NumContrib = employee.getString("NumContrib");
//textView.append(Nome + ", " + String.valueOf(codigo) + ", " + NumContrib + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
response.toString()+"i am queen", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("CodigoInicial","1");
headers.put("C`enter code here`odigoFinal","2");
return headers;
}
};
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
The problem is the implementation of the createHttpRequest method in com.android.volley.toolbox.HttpClientStack.java which will add the body only if the request method is POST, PUT or PATCH.
/**
* Creates the appropriate subclass of HttpUriRequest for passed in request.
*/
#SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Method.DEPRECATED_GET_OR_POST: {
// This is the deprecated way that needs to be handled for backwards compatibility.
// If the request's post body is null, then the assumption is that the request is
// GET. Otherwise, it is assumed that the request is a POST.
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Method.GET:
return new HttpGet(request.getUrl());
case Method.DELETE:
return new HttpDelete(request.getUrl());
case Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Method.HEAD:
return new HttpHead(request.getUrl());
case Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Method.TRACE:
return new HttpTrace(request.getUrl());
case Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrl());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}
So you have to use your own implementation of HttpStack.java or you override HttpClientStack class.
First of all your should replace your initialization of RequestQueue from
RequestQueue requestQueue = Volley.newRequestQueue(sContext);
to
String userAgent = "volley/0";
try {
String packageName = getContext().getPackageName();
PackageInfo info = getContext().getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (PackageManager.NameNotFoundException e) {}
HttpStack httpStack = new OwnHttpClientStack(AndroidHttpClient.newInstance(userAgent));
RequestQueue requesQueue = Volley.newRequestQueue(sContext, httpStack);
and write your own implementation of HttpClientStack where you change the case of "Method.POST:" in the method createHttpRequest(). You also have to create an Object like "OwnHttpDelete" as extention of HttpEntityEnclosingRequestBase to use the method setEntityIfNonEmptyBody().
public class OwnHttpClientStack extends com.android.volley.toolbox.HttpClientStack {
private final static String HEADER_CONTENT_TYPE = "Content-Type";
public OwnHttpClientStack(HttpClient client) {
super(client);
}
#Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
addHeaders(httpRequest, additionalHeaders);
addHeaders(httpRequest, request.getHeaders());
onPrepareRequest(httpRequest);
HttpParams httpParams = httpRequest.getParams();
int timeoutMs = request.getTimeoutMs();
// TODO: Reevaluate this connection timeout based on more wide-scale
// data collection and possibly different for wifi vs. 3G.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
return mClient.execute(httpRequest);
}
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) {
for (String key : headers.keySet()) {
httpRequest.setHeader(key, headers.get(key));
}
}
static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Request.Method.DEPRECATED_GET_OR_POST: {
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Request.Method.GET:
return new HttpGet(request.getUrl());
case Request.Method.DELETE:
OwnHttpDelete deleteRequest = new OwnHttpDelete(request.getUrl());
deleteRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(deleteRequest, request);
return deleteRequest;
case Request.Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Request.Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Request.Method.HEAD:
return new HttpHead(request.getUrl());
case Request.Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Request.Method.TRACE:
return new HttpTrace(request.getUrl());
case Request.Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrl());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private static class OwnHttpDelete extends HttpPost {
public static final String METHOD_NAME = "DELETE";
public OwnHttpDelete() {
super();
}
public OwnHttpDelete(URI uri) {
super(uri);
}
public OwnHttpDelete(String uri) {
super(uri);
}
public String getMethod() {
return METHOD_NAME;
}
}
}
I'm using KSOAP2, when sending request to the server and got java.io.IOException: HTTP request failed, HTTP status: 500 in the line httpTransport.call(SOAP_ACTION, envelope) , but server works, I have checked it using SoapUI. What can be the problem?
public class SOAPClient
{
private static final int TIMEOUT_SOCKET = 180000;
public static SoapObject get(Context context, String methodName, ArrayList<Pair<String, ?>> args) throws Exception
{
final String URL = PrefHelper.getSOAPUrl(context);
final String NAMESPACE = PrefHelper.getSOAPNamespace(context);
final String SOAP_ACTION = methodName; //NAMESPACE + "#" + "mapx" + ":" + methodName;
SoapObjectEve request = new SoapObjectEve(NAMESPACE, methodName);
if (args != null) {
for (Pair<String, ?> arg : args) {
if (arg.first != null) {
request.addProperty(arg.first, arg.second);
}
}
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
new MarshalBase64().register(envelope);
envelope.setOutputSoapObject(request);
envelope.implicitTypes = true;
HttpTransportSE httpTransport = new HttpTransportSE(URL, TIMEOUT_SOCKET);
httpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
try
{
httpTransport.call(SOAP_ACTION, envelope);
AppLog.e(httpTransport.requestDump+"requestDump");
}
catch (ConnectTimeoutException e) {
AppLog.e(e.getMessage());
throw new Exception(context.getString(R.string.node_unavailable));
}
catch (SocketTimeoutException e) {
AppLog.e(e.getMessage());
throw new Exception(context.getString(R.string.timeout));
}
catch (Exception e) {
e.printStackTrace();
AppLog.e(e.getMessage());
AppLog.e(httpTransport.requestDump+"requestDump");
throw new Exception(context.getString(R.string.warning_error_get_data) + e.getMessage() == null ? "" : " " + e.getMessage());
}
AppLog.i(httpTransport.requestDump+"requestDump");
SoapObject soapObj = null;
try {
soapObj = (SoapObject) envelope.getResponse();
}
catch (Exception e) {
String response = ((SoapPrimitive) envelope.getResponse()).toString();
boolean res = Boolean.valueOf(response);
soapObj = new SoapObject();
soapObj.addProperty("response", res);
soapObj.addProperty("msg", "");
soapObj.addProperty("data", null);
}
AppLog.e(httpTransport.responseDump+"responseDump");
return soapObj;
}
}
Make sure your NAMESPACE, METHODNAME, WSDL and SOAP_ACTION are correct.
Try this code,
private static final String NAMESPACE = "http://www.kltro.com";
private static final String METHODNAME = "getUser";
private static final String WSDL = "http://ap.kashkan.org:55555/tro/ws/kltro";
private static final String SOAP_ACTION = NAMESPACE + "#kltro:" + METHODNAME ;
private static String TAG = "soap";
public static String callWebservice() {
String responseDump = "";
try {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject request = new SoapObject(NAMESPACE, METHODNAME);
request.addProperty("login", login);
request.addProperty("pass", password);
request.addProperty("androidID", androidID);
request.addProperty("ver", version);
envelope.bodyOut = request;
HttpTransportSE transport = new HttpTransportSE(WSDL);
transport.debug = true;
try {
transport.call(SOAP_ACTION, envelope);
String requestDump = transport.requestDump;
responseDump = transport.responseDump;
Log.e(TAG, requestDump);
Log.e(TAG, responseDump);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return responseDump;
}
Also make sure you have internet permission in the manifest,
<uses-permission android:name="android.permission.INTERNET" />
I'm developing (trying for now) portlet that will be integrated with LinkedIn.
Following the documentation about it:
http://developer.linkedin.com/docs/DOC-1008 -->
The first step to authorizing a LinkedIn member is requesting a requestToken. This request is done with an HTTP POST.
For the requestToken step, the following components should be present in your string to sign:
* HTTP Method (POST)
* Request URI (https://api.linkedin.com/uas/oauth/requestToken)
* oauth_callback
* oauth_consumer_key
* oauth_nonce
* oauth_signature_method
* oauth_timestamp
* oauth_version
I have already API(it's oauth_consumer_key) key and i need to generate specific URL string.
Have next java code for this URL and HTTP connection:
private void processAuthentication() {
Calendar cal = Calendar.getInstance();
Long ms = cal.getTimeInMillis();
Long timestamp = ms / 1000;
Random r = new Random();
Long nonce = r.nextLong();
String prefixUrl = "https://api.linkedin.com/uas/oauth/requestToken";
String oauthCallback = "oauth_callback=http://localhost/";
String oauthConsumerKey =
"&oauth_consumer_key=my_consumer_key";
String oauthNonce = "&oauth_nonce=" + nonce.toString();
String oauthSignatureMethod = "&oauth_signature_method=HMAC-SHA1";
String oauthTimestamp = "&oauth_timestamp=" + timestamp.toString();
String oauthVersion = "&oauth_version=1.0";
String mainUrl =
oauthCallback + oauthConsumerKey + oauthNonce + oauthSignatureMethod
+ oauthTimestamp + oauthVersion;
try {
prefixUrl =
URLEncoder.encode(prefixUrl, "UTF-8") + "&"
+ URLEncoder.encode(mainUrl, "UTF-8");
URL url = new URL(prefixUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
String msg = connection.getResponseMessage();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The question is next,for those, who had faced this problem:
How should really look URL string for connection and how response is received?
For URL, it's interested the example of URL, you generated.
And for response interested, method to get it.
As i understand, after HTTP connection been established,that response is:
connection.getResponseMessage();
#sergionni I found answer to your Question from linkedin-developer
As you know
The first step to authorizing a Linked-In member is requesting a requestToken. This request is done with an HTTP POST.
Your base string should end up looking something like this if you're using a callback:
POST&https%3A%2F%2Fapi.linkedin.com%2Fuas%2Foauth%2FrequestToken
&oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Foauth_callback%26o
auth_consumer_key%3DABCDEFGHIJKLMNOPQRSTUVWXYZ%26
oauth_nonce%3DoqwgSYFUD87MHmJJDv7bQqOF2EPnVus7Wkqj5duNByU%26
oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1259178158%26
oauth_version%3D1.0
You then sign this base string with your consumer_secret, computing a signature. In this case, if your secret was 1234567890, the signature would be TLQXuUzM7omwDbtXimn6bLDvfF8=.
Now you take the signature you generated, along with oauth_nonce, oauth_callback, oauth_signature_method, oauth_timestamp, oauth_consumer_key, and oauth_version and create an HTTP Authorization header. For this request, that HTTP header would look like:
Authorization: OAuth
oauth_nonce="oqwgSYFUD87MHmJJDv7bQqOF2EPnVus7Wkqj5duNByU",
oauth_callback="http%3A%2F%2Flocalhost%2Foauth_callback",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1259178158",
oauth_consumer_key="ABCDEFGHIJKLMNOPQRSTUVWXYZ",
oauth_signature="TLQXuUzM7omwDbtXimn6bLDvfF8=",
oauth_version="1.0"
Please note, that the HTTP header is a single header -- not an HTTP header for each component. You can optionally supply a realm="http://api.linkedin.com".
As a response to your request for a requestToken, your requestToken will be in the "oauth_token" response field, a validation that we acknowledged your callback with the "oauth_callback_confirmed" field, an oauth_token_secret, and a oauth_expires_in, and a few other values.
(here us Your answaer) response would look like:
oauth_token=94ab03c4-ae2c-45e4-8732-0e6c4899db63
&oauth_token_secret=be6ccb24-bf0a-4ea8-a4b1-0a70508e452b
&oauth_callback_confirmed=true&oauth_expires_in=599
You might try out the OAuth libraries to handle the connection: http://code.google.com/p/oauth/
I created a plugin for Play Framework to easily integrated with LinkedIn's OAuth: geeks.aretotally.in/projects/play-framework-linkedin-module. Hopefully it can help. You should def check out Play, very very cool Java framework.
portlet body:
public class LinkedInPortlet extends GenericPortlet {
public static final String PAGE_PIN = "pin";
public static final String PAGE_EDIT = "edit";
public static final String PAGE_PROFILE = "profile";
public static final String PAGE_CONNECTIONS = "connections";
public static final String FORM_LINKEDIN_PREFERENCES = "preferencesLinkedInForm";
public static final String PAGE_VIEW_MY_PROFILE = "/WEB-INF/portlets/linkedin/myProfile.jsp";
public static final String PAGE_VIEW_MY_CONNECTIONS =
"/WEB-INF/portlets/linkedin/myConnections.jsp";
public static final String PAGE_PREFERENCES = "/WEB-INF/portlets/linkedin/edit.jsp";
public void doView(RenderRequest request, RenderResponse response) throws PortletException,
IOException {
String view = PAGE_VIEW_MY_PROFILE;
String page =
(String) request.getPortletSession().getAttribute(
"page_" + getPortletIdentifier(request), PortletSession.PORTLET_SCOPE);
String accessTokenToken =
getStringConfiguration(request, LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN);
String accessTokenSecret =
getStringConfiguration(request, LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET);
LinkedInContact profile = new LinkedInContact();
List<LinkedInContact> contacts = new ArrayList<LinkedInContact>();
if (PAGE_PIN.equals(page)) {
view = PAGE_PREFERENCES;
} else if (PAGE_EDIT.equals(page)) {
view = PAGE_PREFERENCES;
} else if (PAGE_CONNECTIONS.equals(page)) {
try {
contacts =
ServiceResolver.getResolver().getLinkedInService().getConnections(
accessTokenToken, accessTokenSecret);
} catch (ServiceException se) {
view = PAGE_PREFERENCES;
handleException(request, se);
}
view = PAGE_VIEW_MY_CONNECTIONS;
} else {
try {
profile =
ServiceResolver.getResolver().getLinkedInService().getProfile(
accessTokenToken, accessTokenSecret);
} catch (ServiceException se) {
view = PAGE_PREFERENCES;
handleException(request, se);
}
view = PAGE_VIEW_MY_PROFILE;
}
request.setAttribute("profile", profile);
request.setAttribute("contacts", contacts);
response.setContentType(request.getResponseContentType());
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(view);
rd.include(request, response);
}
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
String action;
action = (String) request.getParameter("action");
String page = request.getParameter("page");
if (page == null) {
page = PAGE_PROFILE;
} else if ("auth".equals(action)) {
request.getPortletSession().setAttribute(
"requestToken_" + getPortletIdentifier(request),
ServiceResolver.getResolver().getLinkedInService().getRequestToken(),
PortletSession.APPLICATION_SCOPE);
LinkedInPreferencesForm form = new LinkedInPreferencesForm(request);
request.getPortletSession().setAttribute(
FORM_LINKEDIN_PREFERENCES + getPortletIdentifier(request), form,
PortletSession.APPLICATION_SCOPE);
response.setPortletMode(PortletMode.EDIT);
} else if ("save".equals(action)) {
try {
try {
savePreferences(request, response);
} catch (ServiceException e) {
handleException(request, e);
}
} catch (PortletModeException e) {
handleException(request, e);
}
} else if ("myProfile".equals(action)) {
page = PAGE_PROFILE;
} else if ("myConnections".equals(action)) {
page = PAGE_CONNECTIONS;
}
if (page != null) {
request.getPortletSession().setAttribute("page_" + getPortletIdentifier(request), page,
PortletSession.PORTLET_SCOPE);
}
}
private void savePreferences(ActionRequest request, ActionResponse response)
throws PortletModeException, ServiceException {
LinkedInPreferencesForm form = new LinkedInPreferencesForm(request);
if (validateForm(request, form)) {
LinkedInRequestToken requestToken =
(LinkedInRequestToken) request.getPortletSession().getAttribute(
"requestToken_" + getPortletIdentifier(request),
PortletSession.APPLICATION_SCOPE);
String pin = request.getParameter("pinCode");
LinkedInAccessToken accessToken;
try {
accessToken =
ServiceResolver.getResolver().getLinkedInService().getAccessToken(
requestToken, pin);
} catch (LinkedInOAuthServiceException ase) {
response.setPortletMode(PortletMode.EDIT);
throw new ServiceException("linkedin.authentication.failed");
}
String tokenToken = requestToken.getToken();
String secret = requestToken.getTokenSecret();
String tokenURL = requestToken.getAuthorizationUrl();
Properties configuration = new Properties();
configuration.setProperty(LinkedInPreferencesForm.PARAM_PIN, form.getPin());
configuration
.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN, tokenToken);
configuration.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET, secret);
configuration.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL, tokenURL);
configuration.setProperty(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN, accessToken
.getToken());
configuration.setProperty(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET,
accessToken.getTokenSecret());
ServiceResolver.getResolver().getPortalService().savePortletConfiguration(request,
configuration);
resetSessionForm(request, FORM_LINKEDIN_PREFERENCES);
response.setPortletMode(PortletMode.VIEW);
} else {
// store in session
request.getPortletSession().setAttribute(
FORM_LINKEDIN_PREFERENCES + getPortletIdentifier(request), form,
PortletSession.APPLICATION_SCOPE);
response.setPortletMode(PortletMode.EDIT);
logger.debug(FORM_LINKEDIN_PREFERENCES + " is in edit mode");
}
}
#Override
protected void addConfiguration(MessageSource messageSource, Locale locale,
Map<String, String> result) {
result.put(LinkedInPreferencesForm.PARAM_PIN, messageSource.getMessage(
"linkedIn.preferences.pin", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN, messageSource.getMessage(
"linkedIn.preferences.requestTokenToken", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET, messageSource.getMessage(
"linkedIn.preferences.requestTokenSecret", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL, messageSource.getMessage(
"linkedIn.preferences.requestTokenURL", null, locale));
result.put(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN, messageSource.getMessage(
"linkedIn.preferences.accessToken", null, locale));
result.put(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET, messageSource.getMessage(
"linkedIn.preferences.accessTokenSecret", null, locale));
}
#Override
protected void addPreference(MessageSource messageSource, Locale locale,
Map<String, String> result) {
}
#Override
public String getAsyncTitle(RenderRequest request) {
return this.getTitle(request);
}
protected boolean validateForm(ActionRequest request, LinkedInPreferencesForm form) {
return form.validate();
}
protected String myEdit(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
LinkedInPreferencesForm form = new LinkedInPreferencesForm();
form.setPin(getStringConfiguration(request, LinkedInPreferencesForm.PARAM_PIN));
form.setRequestTokenToken(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN));
form.setRequestTokenSecret(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET));
form.setRequestTokenURL(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL));
registerSessionForm(request, FORM_LINKEDIN_PREFERENCES, form);
LinkedInRequestToken requestToken;
requestToken =
(LinkedInRequestToken) request.getPortletSession().getAttribute(
"requestToken_" + getPortletIdentifier(request),
PortletSession.APPLICATION_SCOPE);
if (requestToken == null) {
requestToken =
new LinkedInRequestToken(form.getRequestTokenToken(), form
.getRequestTokenSecret());
requestToken.setAuthorizationUrl(form.getRequestTokenURL());
}
request.setAttribute("requestToken", requestToken);
return PAGE_PREFERENCES;
}
}