本文目录一览:
- 1、怎么php发送get请求给Java,然后返回想要的具体参数
- 2、java中get请求和post请求分别请求的对象类型是什么,什么不一样
- 3、java中怎样用post,get,put请求
- 4、JAVA中Get和Post请求的区别收集整理
- 5、java做手机端后台,如何接受get请求参数
怎么php发送get请求给Java,然后返回想要的具体参数
curl请求java接口,接口返回值后进行相关操作,给你贴一个curl的代码
function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) {
$urlset = parse_url($url);
if (empty($urlset['path'])) {
$urlset['path'] = '/';
}
if (!empty($urlset['query'])) {
$urlset['query'] = "?{$urlset['query']}";
}
if (empty($urlset['port'])) {
$urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
}
if (strexists($url, 'https://') !extension_loaded('openssl')) {
if (!extension_loaded("openssl")) {
message('请开启您PHP环境的openssl');
}
}
if (function_exists('curl_init') function_exists('curl_exec')) {
$ch = curl_init();
if (ver_compare(phpversion(), '5.6') = 0) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
}
if (!empty($extra['ip'])) {
$extra['Host'] = $urlset['host'];
$urlset['host'] = $extra['ip'];
unset($extra['ip']);
}
curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
@curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
if ($post) {
if (is_array($post)) {
$filepost = false;
foreach ($post as $name = $value) {
if ((is_string($value) substr($value, 0, 1) == '@') || (class_exists('CURLFile') $value instanceof CURLFile)) {
$filepost = true;
break;
}
}
if (!$filepost) {
$post = http_build_query($post);
}
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
if (!empty($GLOBALS['_W']['config']['setting']['proxy'])) {
$urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
if (!empty($urls['host'])) {
curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
$proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
if (!empty($urls['scheme']) defined($proxytype)) {
curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
} else {
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
}
if (!empty($GLOBALS['_W']['config']['setting']['proxy']['auth'])) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
}
}
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
if (defined('CURL_SSLVERSION_TLSv1')) {
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
}
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
if (!empty($extra) is_array($extra)) {
$headers = array();
foreach ($extra as $opt = $value) {
if (strexists($opt, 'CURLOPT_')) {
curl_setopt($ch, constant($opt), $value);
} elseif (is_numeric($opt)) {
curl_setopt($ch, $opt, $value);
} else {
$headers[] = "{$opt}: {$value}";
}
}
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
}
$data = curl_exec($ch);
$status = curl_getinfo($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno || empty($data)) {
return error(1, $error);
} else {
return ihttp_response_parse($data);
}
}
$method = empty($post) ? 'GET' : 'POST';
$fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
$fdata .= "Host: {$urlset['host']}\r\n";
if (function_exists('gzdecode')) {
$fdata .= "Accept-Encoding: gzip, deflate\r\n";
}
$fdata .= "Connection: close\r\n";
if (!empty($extra) is_array($extra)) {
foreach ($extra as $opt = $value) {
if (!strexists($opt, 'CURLOPT_')) {
$fdata .= "{$opt}: {$value}\r\n";
}
}
}
$body = '';
if ($post) {
if (is_array($post)) {
$body = http_build_query($post);
} else {
$body = urlencode($post);
}
$fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
} else {
$fdata .= "\r\n";
}
if ($urlset['scheme'] == 'https') {
$fp = fsockopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
} else {
$fp = fsockopen($urlset['host'], $urlset['port'], $errno, $error);
}
stream_set_blocking($fp, true);
stream_set_timeout($fp, $timeout);
if (!$fp) {
return error(1, $error);
} else {
fwrite($fp, $fdata);
$content = '';
while (!feof($fp))
$content .= fgets($fp, 512);
fclose($fp);
return ihttp_response_parse($content, true);
}
}
java中get请求和post请求分别请求的对象类型是什么,什么不一样
1. get 是从服务器上获取数据,post 是向服务器传送数据。 get 请求返回 request - URI 所指出的任意信息。
Post 请求用来发送电子邮件、新闻或发送能由交互用户填写的表格。这是唯一需要在请求中发送body的请求。使用Post请求时需要在报文首部 Content - Length 字段中指出body的长度。
2. get 是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址,用户看不到这个过程。
3. 对于 get 方式,服务器端用Request.QueryString获取变量的值,对于 post 方式,服务器端用Request.Form获取提交的数据。
4. get 传送的数据量较小,不能大于2KB。post 传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。 用IIS过滤器的只接受get参数,所以一般大型搜索引擎都是用get方式。
5. get 安全性非常低,post 安全性相对较高。如果这些数据是中文数据而且是非敏感数据,那么使用 get;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用 post 为好。
java中怎样用post,get,put请求
java中用post,get,put请求方法:
public static String javaHttpGet(String url,String charSet){
String resultData = null;
try {
URL pathUrl = new URL(url); //创建一个URL对象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection(); //打开一个HttpURLConnection连接
urlConnect.setConnectTimeout(30000); // 设置连接超时时间
urlConnect.connect();
if (urlConnect.getResponseCode() == 200) { //请求成功
resultData = readInputStream(urlConnect.getInputStream(), charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error("URL出错!", e);
} catch (IOException e) {
LogL.getInstance().getLog().error("读取数据流出错!", e);
}
return resultData;
}
public static String javaHttpPost(String url,MapString,Object map,String charSet){
String resultData=null;
StringBuffer params = new StringBuffer();
try {
IteratorEntryString, Object ir = map.entrySet().iterator();
while (ir.hasNext()) {
Map.EntryString, Object entry = (Map.EntryString, Object) ir.next();
params.append(URLEncoder.encode(entry.getKey(),charSet) + "=" + URLEncoder.encode(entry.getValue().toString(), charSet) + "");
}
byte[] postData = params.deleteCharAt(params.length()).toString().getBytes();
URL pathUrl = new URL(url); //创建一个URL对象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection();
urlConnect.setConnectTimeout(30000); // 设置连接超时时间
urlConnect.setDoOutput(true); //post请求必须设置允许输出
urlConnect.setUseCaches(false); //post请求不能使用缓存
urlConnect.setRequestMethod("POST"); //设置post方式请求
urlConnect.setInstanceFollowRedirects(true);
urlConnect.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset="+charSet);// 配置请求Content-Type
urlConnect.connect(); // 开始连接
DataOutputStream dos = new DataOutputStream(urlConnect.getOutputStream()); // 发送请求参数
dos.write(postData);
dos.flush();
dos.close();
if (urlConnect.getResponseCode() == 200) { //请求成功
resultData = readInputStream(urlConnect.getInputStream(),charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error("URL出错!", e);
} catch (IOException e) {
LogL.getInstance().getLog().error("读取数据流出错!", e);
} catch (Exception e) {
LogL.getInstance().getLog().error("POST出错!", e);
}
return resultData;
}
JAVA中Get和Post请求的区别收集整理
Get:是以实体的方式得到由请求URI所指定资源的信息,如果请求URI只是一个数据产生过程,那么最终要在响应实体中返回的是处理过程的结果所指向的资源,而不是处理过程的描述。
Post:用来向目的服务器发出请求,要求它接受被附在请求后的实体,并把它当作请求队列中请求URI所指定资源的附加新子项,Post被设计成用统一的方法实现下列功能:
1:对现有资源的解释
2:向电子公告栏、新闻组、邮件列表或类似讨论组发信息。
3:提交数据块
4:通过附加操作来扩展数据库
从上面描述可以看出,Get是向服务器发索取数据的一种请求;而Post是向服务器提交数据的一种请求,要提交的数据位于信息头后面的实体中。
java做手机端后台,如何接受get请求参数
package com.weixin.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
//import bsh.ParseException;
import com.google.gson.Gson;
/**
* TODO
* @Version 1.0
*/
public class HttpClients {
/** UTF-8 */
private static final String UTF_8 = "UTF-8";
/** 日志记录tag */
private static final String TAG = "HttpClients";
/** 用户host */
private static String proxyHost = "";
/** 用户端口 */
private static int proxyPort = 80;
/** 是否使用用户端口 */
private static boolean useProxy = false;
/** 连接超时 */
private static final int TIMEOUT_CONNECTION = 60000;
/** 读取超时 */
private static final int TIMEOUT_SOCKET = 60000;
/** 重试3次 */
private static final int RETRY_TIME = 3;
/**
* @param url
* @param requestData
* @return
*/
public String doHtmlPost(HttpClient httpClient,HttpPost httpPost )
{
String responseBody = null;
int statusCode = -1;
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
Header lastHeader = httpResponse.getLastHeader("Set-Cookie");
if(null != lastHeader)
{
httpPost.setHeader("cookie", lastHeader.getValue());
}
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HTTP" + " " + "HttpMethod failed: " + httpResponse.getStatusLine());
}
InputStream is = httpResponse.getEntity().getContent();
responseBody = getStreamAsString(is, HTTP.UTF_8);
} catch (Exception e) {
// 发生网络异常
e.printStackTrace();
} finally {
// httpClient.getConnectionManager().shutdown();
// httpClient = null;
}
return responseBody;
}
/**
*
* 发起网络请求
*
* @param url
* URL
* @param requestData
* requestData
* @return INPUTSTREAM
* @throws AppException
*/
public static String doPost(String url, String requestData) throws Exception {
String responseBody = null;
HttpPost httpPost = null;
HttpClient httpClient = null;
int statusCode = -1;
int time = 0;
do {
try {
httpPost = new HttpPost(url);
httpClient = getHttpClient();
// 设置HTTP POST请求参数必须用NameValuePair对象
ListBasicNameValuePair params = new ArrayListBasicNameValuePair();
params.add(new BasicNameValuePair("param", requestData));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 设置HTTP POST请求参数
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HTTP" + " " + "HttpMethod failed: " + httpResponse.getStatusLine());
}
InputStream is = httpResponse.getEntity().getContent();
responseBody = getStreamAsString(is, HTTP.UTF_8);
break;
} catch (UnsupportedEncodingException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生致命的异常,可能是协议不对或者返回的内容有问题
e.printStackTrace();
} catch (ClientProtocolException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生致命的异常,可能是协议不对或者返回的内容有问题
e.printStackTrace();
} catch (IOException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生网络异常
e.printStackTrace();
} catch (Exception e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生网络异常
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
} while (time RETRY_TIME);
return responseBody;
}
/**
*
* 将InputStream 转化为String
*
* @param stream
* inputstream
* @param charset
* 字符集
* @return
* @throws IOException
*/
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset), 8192);
StringWriter writer = new StringWriter();
char[] chars = new char[8192];
int count = 0;
while ((count = reader.read(chars)) 0) {
writer.write(chars, 0, count);
}
return writer.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
/**
* 得到httpClient
*
* @return
*/
public HttpClient getHttpClient1() {
final HttpParams httpParams = new BasicHttpParams();
if (useProxy) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams, true);
final String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.14) Gecko/20110218 Firefox/3.6.14";
HttpProtocolParams.setUserAgent(httpParams, userAgent);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.RFC_2109);
HttpProtocolParams.setUseExpectContinue(httpParams, false);
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}
/**
*
* 得到httpClient
*
* @return
*/
private static HttpClient getHttpClient() {
final HttpParams httpParams = new BasicHttpParams();
if (useProxy) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams, true);
final String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.14) Gecko/20110218 Firefox/3.6.14";
HttpProtocolParams.setUserAgent(httpParams, userAgent);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY);
HttpProtocolParams.setUseExpectContinue(httpParams, false);
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}
/**
* 打印返回内容
* @param response
* @throws ParseException
* @throws IOException
*/
public static void showResponse(String str) throws Exception {
Gson gson = new Gson();
MapString, Object map = (MapString, Object) gson.fromJson(str, Object.class);
String value = (String) map.get("data");
//String decodeValue = Des3Request.decode(value);
//System.out.println(decodeValue);
//logger.debug(decodeValue);
}
/**
*
* 发起网络请求
*
* @param url
* URL
* @param requestData
* requestData
* @return INPUTSTREAM
* @throws AppException
*/
public static String doGet(String url) throws Exception {
String responseBody = null;
HttpGet httpGet = null;
HttpClient httpClient = null;
int statusCode = -1;
int time = 0;
do {
try {
httpGet = new HttpGet(url);
httpClient = getHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HTTP" + " " + "HttpMethod failed: " + httpResponse.getStatusLine());
}
InputStream is = httpResponse.getEntity().getContent();
responseBody = getStreamAsString(is, HTTP.UTF_8);
break;
} catch (UnsupportedEncodingException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生致命的异常,可能是协议不对或者返回的内容有问题
e.printStackTrace();
} catch (ClientProtocolException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生致命的异常,可能是协议不对或者返回的内容有问题
e.printStackTrace();
} catch (IOException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生网络异常
e.printStackTrace();
} catch (Exception e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 发生网络异常
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
} while (time RETRY_TIME);
return responseBody;
}
}